LLVM  mainline
AsmWriter.cpp
Go to the documentation of this file.
00001 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library implements the functionality defined in llvm/IR/Writer.h
00011 //
00012 // Note that these routines must be extremely tolerant of various errors in the
00013 // LLVM code, because it can be used for debugging transformations.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SetVector.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/IR/AssemblyAnnotationWriter.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/CallingConv.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DebugInfo.h"
00027 #include "llvm/IR/DerivedTypes.h"
00028 #include "llvm/IR/IRPrintingPasses.h"
00029 #include "llvm/IR/InlineAsm.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/IR/Module.h"
00033 #include "llvm/IR/ModuleSlotTracker.h"
00034 #include "llvm/IR/Operator.h"
00035 #include "llvm/IR/Statepoint.h"
00036 #include "llvm/IR/TypeFinder.h"
00037 #include "llvm/IR/UseListOrder.h"
00038 #include "llvm/IR/ValueSymbolTable.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/Dwarf.h"
00041 #include "llvm/Support/ErrorHandling.h"
00042 #include "llvm/Support/Format.h"
00043 #include "llvm/Support/FormattedStream.h"
00044 #include "llvm/Support/MathExtras.h"
00045 #include "llvm/Support/raw_ostream.h"
00046 #include <algorithm>
00047 #include <cctype>
00048 using namespace llvm;
00049 
00050 // Make virtual table appear in this compilation unit.
00051 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
00052 
00053 //===----------------------------------------------------------------------===//
00054 // Helper Functions
00055 //===----------------------------------------------------------------------===//
00056 
00057 namespace {
00058 struct OrderMap {
00059   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
00060 
00061   unsigned size() const { return IDs.size(); }
00062   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
00063   std::pair<unsigned, bool> lookup(const Value *V) const {
00064     return IDs.lookup(V);
00065   }
00066   void index(const Value *V) {
00067     // Explicitly sequence get-size and insert-value operations to avoid UB.
00068     unsigned ID = IDs.size() + 1;
00069     IDs[V].first = ID;
00070   }
00071 };
00072 }
00073 
00074 static void orderValue(const Value *V, OrderMap &OM) {
00075   if (OM.lookup(V).first)
00076     return;
00077 
00078   if (const Constant *C = dyn_cast<Constant>(V))
00079     if (C->getNumOperands() && !isa<GlobalValue>(C))
00080       for (const Value *Op : C->operands())
00081         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
00082           orderValue(Op, OM);
00083 
00084   // Note: we cannot cache this lookup above, since inserting into the map
00085   // changes the map's size, and thus affects the other IDs.
00086   OM.index(V);
00087 }
00088 
00089 static OrderMap orderModule(const Module *M) {
00090   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
00091   // and ValueEnumerator::incorporateFunction().
00092   OrderMap OM;
00093 
00094   for (const GlobalVariable &G : M->globals()) {
00095     if (G.hasInitializer())
00096       if (!isa<GlobalValue>(G.getInitializer()))
00097         orderValue(G.getInitializer(), OM);
00098     orderValue(&G, OM);
00099   }
00100   for (const GlobalAlias &A : M->aliases()) {
00101     if (!isa<GlobalValue>(A.getAliasee()))
00102       orderValue(A.getAliasee(), OM);
00103     orderValue(&A, OM);
00104   }
00105   for (const Function &F : *M) {
00106     for (const Use &U : F.operands())
00107       if (!isa<GlobalValue>(U.get()))
00108         orderValue(U.get(), OM);
00109 
00110     orderValue(&F, OM);
00111 
00112     if (F.isDeclaration())
00113       continue;
00114 
00115     for (const Argument &A : F.args())
00116       orderValue(&A, OM);
00117     for (const BasicBlock &BB : F) {
00118       orderValue(&BB, OM);
00119       for (const Instruction &I : BB) {
00120         for (const Value *Op : I.operands())
00121           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
00122               isa<InlineAsm>(*Op))
00123             orderValue(Op, OM);
00124         orderValue(&I, OM);
00125       }
00126     }
00127   }
00128   return OM;
00129 }
00130 
00131 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
00132                                          unsigned ID, const OrderMap &OM,
00133                                          UseListOrderStack &Stack) {
00134   // Predict use-list order for this one.
00135   typedef std::pair<const Use *, unsigned> Entry;
00136   SmallVector<Entry, 64> List;
00137   for (const Use &U : V->uses())
00138     // Check if this user will be serialized.
00139     if (OM.lookup(U.getUser()).first)
00140       List.push_back(std::make_pair(&U, List.size()));
00141 
00142   if (List.size() < 2)
00143     // We may have lost some users.
00144     return;
00145 
00146   bool GetsReversed =
00147       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
00148   if (auto *BA = dyn_cast<BlockAddress>(V))
00149     ID = OM.lookup(BA->getBasicBlock()).first;
00150   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
00151     const Use *LU = L.first;
00152     const Use *RU = R.first;
00153     if (LU == RU)
00154       return false;
00155 
00156     auto LID = OM.lookup(LU->getUser()).first;
00157     auto RID = OM.lookup(RU->getUser()).first;
00158 
00159     // If ID is 4, then expect: 7 6 5 1 2 3.
00160     if (LID < RID) {
00161       if (GetsReversed)
00162         if (RID <= ID)
00163           return true;
00164       return false;
00165     }
00166     if (RID < LID) {
00167       if (GetsReversed)
00168         if (LID <= ID)
00169           return false;
00170       return true;
00171     }
00172 
00173     // LID and RID are equal, so we have different operands of the same user.
00174     // Assume operands are added in order for all instructions.
00175     if (GetsReversed)
00176       if (LID <= ID)
00177         return LU->getOperandNo() < RU->getOperandNo();
00178     return LU->getOperandNo() > RU->getOperandNo();
00179   });
00180 
00181   if (std::is_sorted(
00182           List.begin(), List.end(),
00183           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
00184     // Order is already correct.
00185     return;
00186 
00187   // Store the shuffle.
00188   Stack.emplace_back(V, F, List.size());
00189   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
00190   for (size_t I = 0, E = List.size(); I != E; ++I)
00191     Stack.back().Shuffle[I] = List[I].second;
00192 }
00193 
00194 static void predictValueUseListOrder(const Value *V, const Function *F,
00195                                      OrderMap &OM, UseListOrderStack &Stack) {
00196   auto &IDPair = OM[V];
00197   assert(IDPair.first && "Unmapped value");
00198   if (IDPair.second)
00199     // Already predicted.
00200     return;
00201 
00202   // Do the actual prediction.
00203   IDPair.second = true;
00204   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
00205     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
00206 
00207   // Recursive descent into constants.
00208   if (const Constant *C = dyn_cast<Constant>(V))
00209     if (C->getNumOperands()) // Visit GlobalValues.
00210       for (const Value *Op : C->operands())
00211         if (isa<Constant>(Op)) // Visit GlobalValues.
00212           predictValueUseListOrder(Op, F, OM, Stack);
00213 }
00214 
00215 static UseListOrderStack predictUseListOrder(const Module *M) {
00216   OrderMap OM = orderModule(M);
00217 
00218   // Use-list orders need to be serialized after all the users have been added
00219   // to a value, or else the shuffles will be incomplete.  Store them per
00220   // function in a stack.
00221   //
00222   // Aside from function order, the order of values doesn't matter much here.
00223   UseListOrderStack Stack;
00224 
00225   // We want to visit the functions backward now so we can list function-local
00226   // constants in the last Function they're used in.  Module-level constants
00227   // have already been visited above.
00228   for (const Function &F : make_range(M->rbegin(), M->rend())) {
00229     if (F.isDeclaration())
00230       continue;
00231     for (const BasicBlock &BB : F)
00232       predictValueUseListOrder(&BB, &F, OM, Stack);
00233     for (const Argument &A : F.args())
00234       predictValueUseListOrder(&A, &F, OM, Stack);
00235     for (const BasicBlock &BB : F)
00236       for (const Instruction &I : BB)
00237         for (const Value *Op : I.operands())
00238           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
00239             predictValueUseListOrder(Op, &F, OM, Stack);
00240     for (const BasicBlock &BB : F)
00241       for (const Instruction &I : BB)
00242         predictValueUseListOrder(&I, &F, OM, Stack);
00243   }
00244 
00245   // Visit globals last.
00246   for (const GlobalVariable &G : M->globals())
00247     predictValueUseListOrder(&G, nullptr, OM, Stack);
00248   for (const Function &F : *M)
00249     predictValueUseListOrder(&F, nullptr, OM, Stack);
00250   for (const GlobalAlias &A : M->aliases())
00251     predictValueUseListOrder(&A, nullptr, OM, Stack);
00252   for (const GlobalVariable &G : M->globals())
00253     if (G.hasInitializer())
00254       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
00255   for (const GlobalAlias &A : M->aliases())
00256     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
00257   for (const Function &F : *M)
00258     for (const Use &U : F.operands())
00259       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
00260 
00261   return Stack;
00262 }
00263 
00264 static const Module *getModuleFromVal(const Value *V) {
00265   if (const Argument *MA = dyn_cast<Argument>(V))
00266     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
00267 
00268   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00269     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
00270 
00271   if (const Instruction *I = dyn_cast<Instruction>(V)) {
00272     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
00273     return M ? M->getParent() : nullptr;
00274   }
00275 
00276   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00277     return GV->getParent();
00278 
00279   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
00280     for (const User *U : MAV->users())
00281       if (isa<Instruction>(U))
00282         if (const Module *M = getModuleFromVal(U))
00283           return M;
00284     return nullptr;
00285   }
00286 
00287   return nullptr;
00288 }
00289 
00290 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
00291   switch (cc) {
00292   default:                         Out << "cc" << cc; break;
00293   case CallingConv::Fast:          Out << "fastcc"; break;
00294   case CallingConv::Cold:          Out << "coldcc"; break;
00295   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
00296   case CallingConv::AnyReg:        Out << "anyregcc"; break;
00297   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
00298   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
00299   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
00300   case CallingConv::GHC:           Out << "ghccc"; break;
00301   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
00302   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
00303   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
00304   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
00305   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
00306   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
00307   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
00308   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
00309   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
00310   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
00311   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
00312   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
00313   case CallingConv::X86_64_Win64:  Out << "x86_64_win64cc"; break;
00314   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
00315   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
00316   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
00317   case CallingConv::HHVM:          Out << "hhvmcc"; break;
00318   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
00319   }
00320 }
00321 
00322 // PrintEscapedString - Print each character of the specified string, escaping
00323 // it if it is not printable or if it is an escape char.
00324 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
00325   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00326     unsigned char C = Name[i];
00327     if (isprint(C) && C != '\\' && C != '"')
00328       Out << C;
00329     else
00330       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
00331   }
00332 }
00333 
00334 enum PrefixType {
00335   GlobalPrefix,
00336   ComdatPrefix,
00337   LabelPrefix,
00338   LocalPrefix,
00339   NoPrefix
00340 };
00341 
00342 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
00343   assert(!Name.empty() && "Cannot get empty name!");
00344 
00345   // Scan the name to see if it needs quotes first.
00346   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
00347   if (!NeedsQuotes) {
00348     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00349       // By making this unsigned, the value passed in to isalnum will always be
00350       // in the range 0-255.  This is important when building with MSVC because
00351       // its implementation will assert.  This situation can arise when dealing
00352       // with UTF-8 multibyte characters.
00353       unsigned char C = Name[i];
00354       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
00355           C != '_') {
00356         NeedsQuotes = true;
00357         break;
00358       }
00359     }
00360   }
00361 
00362   // If we didn't need any quotes, just write out the name in one blast.
00363   if (!NeedsQuotes) {
00364     OS << Name;
00365     return;
00366   }
00367 
00368   // Okay, we need quotes.  Output the quotes and escape any scary characters as
00369   // needed.
00370   OS << '"';
00371   PrintEscapedString(Name, OS);
00372   OS << '"';
00373 }
00374 
00375 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
00376 /// (if the string only contains simple characters) or is surrounded with ""'s
00377 /// (if it has special chars in it). Print it out.
00378 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
00379   switch (Prefix) {
00380   case NoPrefix:
00381     break;
00382   case GlobalPrefix:
00383     OS << '@';
00384     break;
00385   case ComdatPrefix:
00386     OS << '$';
00387     break;
00388   case LabelPrefix:
00389     break;
00390   case LocalPrefix:
00391     OS << '%';
00392     break;
00393   }
00394   printLLVMNameWithoutPrefix(OS, Name);
00395 }
00396 
00397 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
00398 /// (if the string only contains simple characters) or is surrounded with ""'s
00399 /// (if it has special chars in it). Print it out.
00400 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
00401   PrintLLVMName(OS, V->getName(),
00402                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
00403 }
00404 
00405 
00406 namespace {
00407 class TypePrinting {
00408   TypePrinting(const TypePrinting &) = delete;
00409   void operator=(const TypePrinting&) = delete;
00410 public:
00411 
00412   /// NamedTypes - The named types that are used by the current module.
00413   TypeFinder NamedTypes;
00414 
00415   /// NumberedTypes - The numbered types, along with their value.
00416   DenseMap<StructType*, unsigned> NumberedTypes;
00417 
00418   TypePrinting() = default;
00419 
00420   void incorporateTypes(const Module &M);
00421 
00422   void print(Type *Ty, raw_ostream &OS);
00423 
00424   void printStructBody(StructType *Ty, raw_ostream &OS);
00425 };
00426 } // namespace
00427 
00428 void TypePrinting::incorporateTypes(const Module &M) {
00429   NamedTypes.run(M, false);
00430 
00431   // The list of struct types we got back includes all the struct types, split
00432   // the unnamed ones out to a numbering and remove the anonymous structs.
00433   unsigned NextNumber = 0;
00434 
00435   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
00436   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
00437     StructType *STy = *I;
00438 
00439     // Ignore anonymous types.
00440     if (STy->isLiteral())
00441       continue;
00442 
00443     if (STy->getName().empty())
00444       NumberedTypes[STy] = NextNumber++;
00445     else
00446       *NextToUse++ = STy;
00447   }
00448 
00449   NamedTypes.erase(NextToUse, NamedTypes.end());
00450 }
00451 
00452 
00453 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
00454 /// use of type names or up references to shorten the type name where possible.
00455 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
00456   switch (Ty->getTypeID()) {
00457   case Type::VoidTyID:      OS << "void"; return;
00458   case Type::HalfTyID:      OS << "half"; return;
00459   case Type::FloatTyID:     OS << "float"; return;
00460   case Type::DoubleTyID:    OS << "double"; return;
00461   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
00462   case Type::FP128TyID:     OS << "fp128"; return;
00463   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
00464   case Type::LabelTyID:     OS << "label"; return;
00465   case Type::MetadataTyID:  OS << "metadata"; return;
00466   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
00467   case Type::TokenTyID:     OS << "token"; return;
00468   case Type::IntegerTyID:
00469     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
00470     return;
00471 
00472   case Type::FunctionTyID: {
00473     FunctionType *FTy = cast<FunctionType>(Ty);
00474     print(FTy->getReturnType(), OS);
00475     OS << " (";
00476     for (FunctionType::param_iterator I = FTy->param_begin(),
00477          E = FTy->param_end(); I != E; ++I) {
00478       if (I != FTy->param_begin())
00479         OS << ", ";
00480       print(*I, OS);
00481     }
00482     if (FTy->isVarArg()) {
00483       if (FTy->getNumParams()) OS << ", ";
00484       OS << "...";
00485     }
00486     OS << ')';
00487     return;
00488   }
00489   case Type::StructTyID: {
00490     StructType *STy = cast<StructType>(Ty);
00491 
00492     if (STy->isLiteral())
00493       return printStructBody(STy, OS);
00494 
00495     if (!STy->getName().empty())
00496       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
00497 
00498     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
00499     if (I != NumberedTypes.end())
00500       OS << '%' << I->second;
00501     else  // Not enumerated, print the hex address.
00502       OS << "%\"type " << STy << '\"';
00503     return;
00504   }
00505   case Type::PointerTyID: {
00506     PointerType *PTy = cast<PointerType>(Ty);
00507     print(PTy->getElementType(), OS);
00508     if (unsigned AddressSpace = PTy->getAddressSpace())
00509       OS << " addrspace(" << AddressSpace << ')';
00510     OS << '*';
00511     return;
00512   }
00513   case Type::ArrayTyID: {
00514     ArrayType *ATy = cast<ArrayType>(Ty);
00515     OS << '[' << ATy->getNumElements() << " x ";
00516     print(ATy->getElementType(), OS);
00517     OS << ']';
00518     return;
00519   }
00520   case Type::VectorTyID: {
00521     VectorType *PTy = cast<VectorType>(Ty);
00522     OS << "<" << PTy->getNumElements() << " x ";
00523     print(PTy->getElementType(), OS);
00524     OS << '>';
00525     return;
00526   }
00527   }
00528   llvm_unreachable("Invalid TypeID");
00529 }
00530 
00531 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
00532   if (STy->isOpaque()) {
00533     OS << "opaque";
00534     return;
00535   }
00536 
00537   if (STy->isPacked())
00538     OS << '<';
00539 
00540   if (STy->getNumElements() == 0) {
00541     OS << "{}";
00542   } else {
00543     StructType::element_iterator I = STy->element_begin();
00544     OS << "{ ";
00545     print(*I++, OS);
00546     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
00547       OS << ", ";
00548       print(*I, OS);
00549     }
00550 
00551     OS << " }";
00552   }
00553   if (STy->isPacked())
00554     OS << '>';
00555 }
00556 
00557 namespace llvm {
00558 //===----------------------------------------------------------------------===//
00559 // SlotTracker Class: Enumerate slot numbers for unnamed values
00560 //===----------------------------------------------------------------------===//
00561 /// This class provides computation of slot numbers for LLVM Assembly writing.
00562 ///
00563 class SlotTracker {
00564 public:
00565   /// ValueMap - A mapping of Values to slot numbers.
00566   typedef DenseMap<const Value*, unsigned> ValueMap;
00567 
00568 private:
00569   /// TheModule - The module for which we are holding slot numbers.
00570   const Module* TheModule;
00571 
00572   /// TheFunction - The function for which we are holding slot numbers.
00573   const Function* TheFunction;
00574   bool FunctionProcessed;
00575   bool ShouldInitializeAllMetadata;
00576 
00577   /// mMap - The slot map for the module level data.
00578   ValueMap mMap;
00579   unsigned mNext;
00580 
00581   /// fMap - The slot map for the function level data.
00582   ValueMap fMap;
00583   unsigned fNext;
00584 
00585   /// mdnMap - Map for MDNodes.
00586   DenseMap<const MDNode*, unsigned> mdnMap;
00587   unsigned mdnNext;
00588 
00589   /// asMap - The slot map for attribute sets.
00590   DenseMap<AttributeSet, unsigned> asMap;
00591   unsigned asNext;
00592 public:
00593   /// Construct from a module.
00594   ///
00595   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
00596   /// functions, giving correct numbering for metadata referenced only from
00597   /// within a function (even if no functions have been initialized).
00598   explicit SlotTracker(const Module *M,
00599                        bool ShouldInitializeAllMetadata = false);
00600   /// Construct from a function, starting out in incorp state.
00601   ///
00602   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
00603   /// functions, giving correct numbering for metadata referenced only from
00604   /// within a function (even if no functions have been initialized).
00605   explicit SlotTracker(const Function *F,
00606                        bool ShouldInitializeAllMetadata = false);
00607 
00608   /// Return the slot number of the specified value in it's type
00609   /// plane.  If something is not in the SlotTracker, return -1.
00610   int getLocalSlot(const Value *V);
00611   int getGlobalSlot(const GlobalValue *V);
00612   int getMetadataSlot(const MDNode *N);
00613   int getAttributeGroupSlot(AttributeSet AS);
00614 
00615   /// If you'd like to deal with a function instead of just a module, use
00616   /// this method to get its data into the SlotTracker.
00617   void incorporateFunction(const Function *F) {
00618     TheFunction = F;
00619     FunctionProcessed = false;
00620   }
00621 
00622   const Function *getFunction() const { return TheFunction; }
00623 
00624   /// After calling incorporateFunction, use this method to remove the
00625   /// most recently incorporated function from the SlotTracker. This
00626   /// will reset the state of the machine back to just the module contents.
00627   void purgeFunction();
00628 
00629   /// MDNode map iterators.
00630   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
00631   mdn_iterator mdn_begin() { return mdnMap.begin(); }
00632   mdn_iterator mdn_end() { return mdnMap.end(); }
00633   unsigned mdn_size() const { return mdnMap.size(); }
00634   bool mdn_empty() const { return mdnMap.empty(); }
00635 
00636   /// AttributeSet map iterators.
00637   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
00638   as_iterator as_begin()   { return asMap.begin(); }
00639   as_iterator as_end()     { return asMap.end(); }
00640   unsigned as_size() const { return asMap.size(); }
00641   bool as_empty() const    { return asMap.empty(); }
00642 
00643   /// This function does the actual initialization.
00644   inline void initialize();
00645 
00646   // Implementation Details
00647 private:
00648   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00649   void CreateModuleSlot(const GlobalValue *V);
00650 
00651   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
00652   void CreateMetadataSlot(const MDNode *N);
00653 
00654   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
00655   void CreateFunctionSlot(const Value *V);
00656 
00657   /// \brief Insert the specified AttributeSet into the slot table.
00658   void CreateAttributeSetSlot(AttributeSet AS);
00659 
00660   /// Add all of the module level global variables (and their initializers)
00661   /// and function declarations, but not the contents of those functions.
00662   void processModule();
00663 
00664   /// Add all of the functions arguments, basic blocks, and instructions.
00665   void processFunction();
00666 
00667   /// Add all of the metadata from a function.
00668   void processFunctionMetadata(const Function &F);
00669 
00670   /// Add all of the metadata from an instruction.
00671   void processInstructionMetadata(const Instruction &I);
00672 
00673   SlotTracker(const SlotTracker &) = delete;
00674   void operator=(const SlotTracker &) = delete;
00675 };
00676 } // namespace llvm
00677 
00678 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
00679                                      const Function *F)
00680     : M(M), F(F), Machine(&Machine) {}
00681 
00682 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
00683                                      bool ShouldInitializeAllMetadata)
00684     : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
00685                        : nullptr),
00686       M(M), Machine(MachineStorage.get()) {}
00687 
00688 ModuleSlotTracker::~ModuleSlotTracker() {}
00689 
00690 void ModuleSlotTracker::incorporateFunction(const Function &F) {
00691   if (!Machine)
00692     return;
00693 
00694   // Nothing to do if this is the right function already.
00695   if (this->F == &F)
00696     return;
00697   if (this->F)
00698     Machine->purgeFunction();
00699   Machine->incorporateFunction(&F);
00700   this->F = &F;
00701 }
00702 
00703 int ModuleSlotTracker::getLocalSlot(const Value *V) {
00704   assert(F && "No function incorporated");
00705   return Machine->getLocalSlot(V);
00706 }
00707 
00708 static SlotTracker *createSlotTracker(const Value *V) {
00709   if (const Argument *FA = dyn_cast<Argument>(V))
00710     return new SlotTracker(FA->getParent());
00711 
00712   if (const Instruction *I = dyn_cast<Instruction>(V))
00713     if (I->getParent())
00714       return new SlotTracker(I->getParent()->getParent());
00715 
00716   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00717     return new SlotTracker(BB->getParent());
00718 
00719   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00720     return new SlotTracker(GV->getParent());
00721 
00722   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00723     return new SlotTracker(GA->getParent());
00724 
00725   if (const Function *Func = dyn_cast<Function>(V))
00726     return new SlotTracker(Func);
00727 
00728   return nullptr;
00729 }
00730 
00731 #if 0
00732 #define ST_DEBUG(X) dbgs() << X
00733 #else
00734 #define ST_DEBUG(X)
00735 #endif
00736 
00737 // Module level constructor. Causes the contents of the Module (sans functions)
00738 // to be added to the slot table.
00739 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
00740     : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
00741       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
00742       fNext(0), mdnNext(0), asNext(0) {}
00743 
00744 // Function level constructor. Causes the contents of the Module and the one
00745 // function provided to be added to the slot table.
00746 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
00747     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
00748       FunctionProcessed(false),
00749       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
00750       fNext(0), mdnNext(0), asNext(0) {}
00751 
00752 inline void SlotTracker::initialize() {
00753   if (TheModule) {
00754     processModule();
00755     TheModule = nullptr; ///< Prevent re-processing next time we're called.
00756   }
00757 
00758   if (TheFunction && !FunctionProcessed)
00759     processFunction();
00760 }
00761 
00762 // Iterate through all the global variables, functions, and global
00763 // variable initializers and create slots for them.
00764 void SlotTracker::processModule() {
00765   ST_DEBUG("begin processModule!\n");
00766 
00767   // Add all of the unnamed global variables to the value table.
00768   for (const GlobalVariable &Var : TheModule->globals()) {
00769     if (!Var.hasName())
00770       CreateModuleSlot(&Var);
00771   }
00772 
00773   for (const GlobalAlias &A : TheModule->aliases()) {
00774     if (!A.hasName())
00775       CreateModuleSlot(&A);
00776   }
00777 
00778   // Add metadata used by named metadata.
00779   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
00780     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
00781       CreateMetadataSlot(NMD.getOperand(i));
00782   }
00783 
00784   for (const Function &F : *TheModule) {
00785     if (!F.hasName())
00786       // Add all the unnamed functions to the table.
00787       CreateModuleSlot(&F);
00788 
00789     if (ShouldInitializeAllMetadata)
00790       processFunctionMetadata(F);
00791 
00792     // Add all the function attributes to the table.
00793     // FIXME: Add attributes of other objects?
00794     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
00795     if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
00796       CreateAttributeSetSlot(FnAttrs);
00797   }
00798 
00799   ST_DEBUG("end processModule!\n");
00800 }
00801 
00802 // Process the arguments, basic blocks, and instructions  of a function.
00803 void SlotTracker::processFunction() {
00804   ST_DEBUG("begin processFunction!\n");
00805   fNext = 0;
00806 
00807   // Process function metadata if it wasn't hit at the module-level.
00808   if (!ShouldInitializeAllMetadata)
00809     processFunctionMetadata(*TheFunction);
00810 
00811   // Add all the function arguments with no names.
00812   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
00813       AE = TheFunction->arg_end(); AI != AE; ++AI)
00814     if (!AI->hasName())
00815       CreateFunctionSlot(&*AI);
00816 
00817   ST_DEBUG("Inserting Instructions:\n");
00818 
00819   // Add all of the basic blocks and instructions with no names.
00820   for (auto &BB : *TheFunction) {
00821     if (!BB.hasName())
00822       CreateFunctionSlot(&BB);
00823 
00824     for (auto &I : BB) {
00825       if (!I.getType()->isVoidTy() && !I.hasName())
00826         CreateFunctionSlot(&I);
00827 
00828       // We allow direct calls to any llvm.foo function here, because the
00829       // target may not be linked into the optimizer.
00830       if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
00831         // Add all the call attributes to the table.
00832         AttributeSet Attrs = CI->getAttributes().getFnAttributes();
00833         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00834           CreateAttributeSetSlot(Attrs);
00835       } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
00836         // Add all the call attributes to the table.
00837         AttributeSet Attrs = II->getAttributes().getFnAttributes();
00838         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00839           CreateAttributeSetSlot(Attrs);
00840       }
00841     }
00842   }
00843 
00844   FunctionProcessed = true;
00845 
00846   ST_DEBUG("end processFunction!\n");
00847 }
00848 
00849 void SlotTracker::processFunctionMetadata(const Function &F) {
00850   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00851   F.getAllMetadata(MDs);
00852   for (auto &MD : MDs)
00853     CreateMetadataSlot(MD.second);
00854 
00855   for (auto &BB : F) {
00856     for (auto &I : BB)
00857       processInstructionMetadata(I);
00858   }
00859 }
00860 
00861 void SlotTracker::processInstructionMetadata(const Instruction &I) {
00862   // Process metadata used directly by intrinsics.
00863   if (const CallInst *CI = dyn_cast<CallInst>(&I))
00864     if (Function *F = CI->getCalledFunction())
00865       if (F->isIntrinsic())
00866         for (auto &Op : I.operands())
00867           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
00868             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
00869               CreateMetadataSlot(N);
00870 
00871   // Process metadata attached to this instruction.
00872   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00873   I.getAllMetadata(MDs);
00874   for (auto &MD : MDs)
00875     CreateMetadataSlot(MD.second);
00876 }
00877 
00878 /// Clean up after incorporating a function. This is the only way to get out of
00879 /// the function incorporation state that affects get*Slot/Create*Slot. Function
00880 /// incorporation state is indicated by TheFunction != 0.
00881 void SlotTracker::purgeFunction() {
00882   ST_DEBUG("begin purgeFunction!\n");
00883   fMap.clear(); // Simply discard the function level map
00884   TheFunction = nullptr;
00885   FunctionProcessed = false;
00886   ST_DEBUG("end purgeFunction!\n");
00887 }
00888 
00889 /// getGlobalSlot - Get the slot number of a global value.
00890 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
00891   // Check for uninitialized state and do lazy initialization.
00892   initialize();
00893 
00894   // Find the value in the module map
00895   ValueMap::iterator MI = mMap.find(V);
00896   return MI == mMap.end() ? -1 : (int)MI->second;
00897 }
00898 
00899 /// getMetadataSlot - Get the slot number of a MDNode.
00900 int SlotTracker::getMetadataSlot(const MDNode *N) {
00901   // Check for uninitialized state and do lazy initialization.
00902   initialize();
00903 
00904   // Find the MDNode in the module map
00905   mdn_iterator MI = mdnMap.find(N);
00906   return MI == mdnMap.end() ? -1 : (int)MI->second;
00907 }
00908 
00909 
00910 /// getLocalSlot - Get the slot number for a value that is local to a function.
00911 int SlotTracker::getLocalSlot(const Value *V) {
00912   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
00913 
00914   // Check for uninitialized state and do lazy initialization.
00915   initialize();
00916 
00917   ValueMap::iterator FI = fMap.find(V);
00918   return FI == fMap.end() ? -1 : (int)FI->second;
00919 }
00920 
00921 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
00922   // Check for uninitialized state and do lazy initialization.
00923   initialize();
00924 
00925   // Find the AttributeSet in the module map.
00926   as_iterator AI = asMap.find(AS);
00927   return AI == asMap.end() ? -1 : (int)AI->second;
00928 }
00929 
00930 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00931 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
00932   assert(V && "Can't insert a null Value into SlotTracker!");
00933   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
00934   assert(!V->hasName() && "Doesn't need a slot!");
00935 
00936   unsigned DestSlot = mNext++;
00937   mMap[V] = DestSlot;
00938 
00939   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00940            DestSlot << " [");
00941   // G = Global, F = Function, A = Alias, o = other
00942   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
00943             (isa<Function>(V) ? 'F' :
00944              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
00945 }
00946 
00947 /// CreateSlot - Create a new slot for the specified value if it has no name.
00948 void SlotTracker::CreateFunctionSlot(const Value *V) {
00949   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
00950 
00951   unsigned DestSlot = fNext++;
00952   fMap[V] = DestSlot;
00953 
00954   // G = Global, F = Function, o = other
00955   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00956            DestSlot << " [o]\n");
00957 }
00958 
00959 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
00960 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
00961   assert(N && "Can't insert a null Value into SlotTracker!");
00962 
00963   unsigned DestSlot = mdnNext;
00964   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
00965     return;
00966   ++mdnNext;
00967 
00968   // Recursively add any MDNodes referenced by operands.
00969   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00970     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
00971       CreateMetadataSlot(Op);
00972 }
00973 
00974 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
00975   assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
00976          "Doesn't need a slot!");
00977 
00978   as_iterator I = asMap.find(AS);
00979   if (I != asMap.end())
00980     return;
00981 
00982   unsigned DestSlot = asNext++;
00983   asMap[AS] = DestSlot;
00984 }
00985 
00986 //===----------------------------------------------------------------------===//
00987 // AsmWriter Implementation
00988 //===----------------------------------------------------------------------===//
00989 
00990 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
00991                                    TypePrinting *TypePrinter,
00992                                    SlotTracker *Machine,
00993                                    const Module *Context);
00994 
00995 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
00996                                    TypePrinting *TypePrinter,
00997                                    SlotTracker *Machine, const Module *Context,
00998                                    bool FromValue = false);
00999 
01000 static const char *getPredicateText(unsigned predicate) {
01001   const char * pred = "unknown";
01002   switch (predicate) {
01003   case FCmpInst::FCMP_FALSE: pred = "false"; break;
01004   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
01005   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
01006   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
01007   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
01008   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
01009   case FCmpInst::FCMP_ONE:   pred = "one"; break;
01010   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
01011   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
01012   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
01013   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
01014   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
01015   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
01016   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
01017   case FCmpInst::FCMP_UNE:   pred = "une"; break;
01018   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
01019   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
01020   case ICmpInst::ICMP_NE:    pred = "ne"; break;
01021   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
01022   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
01023   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
01024   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
01025   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
01026   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
01027   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
01028   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
01029   }
01030   return pred;
01031 }
01032 
01033 static void writeAtomicRMWOperation(raw_ostream &Out,
01034                                     AtomicRMWInst::BinOp Op) {
01035   switch (Op) {
01036   default: Out << " <unknown operation " << Op << ">"; break;
01037   case AtomicRMWInst::Xchg: Out << " xchg"; break;
01038   case AtomicRMWInst::Add:  Out << " add"; break;
01039   case AtomicRMWInst::Sub:  Out << " sub"; break;
01040   case AtomicRMWInst::And:  Out << " and"; break;
01041   case AtomicRMWInst::Nand: Out << " nand"; break;
01042   case AtomicRMWInst::Or:   Out << " or"; break;
01043   case AtomicRMWInst::Xor:  Out << " xor"; break;
01044   case AtomicRMWInst::Max:  Out << " max"; break;
01045   case AtomicRMWInst::Min:  Out << " min"; break;
01046   case AtomicRMWInst::UMax: Out << " umax"; break;
01047   case AtomicRMWInst::UMin: Out << " umin"; break;
01048   }
01049 }
01050 
01051 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
01052   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
01053     // Unsafe algebra implies all the others, no need to write them all out
01054     if (FPO->hasUnsafeAlgebra())
01055       Out << " fast";
01056     else {
01057       if (FPO->hasNoNaNs())
01058         Out << " nnan";
01059       if (FPO->hasNoInfs())
01060         Out << " ninf";
01061       if (FPO->hasNoSignedZeros())
01062         Out << " nsz";
01063       if (FPO->hasAllowReciprocal())
01064         Out << " arcp";
01065     }
01066   }
01067 
01068   if (const OverflowingBinaryOperator *OBO =
01069         dyn_cast<OverflowingBinaryOperator>(U)) {
01070     if (OBO->hasNoUnsignedWrap())
01071       Out << " nuw";
01072     if (OBO->hasNoSignedWrap())
01073       Out << " nsw";
01074   } else if (const PossiblyExactOperator *Div =
01075                dyn_cast<PossiblyExactOperator>(U)) {
01076     if (Div->isExact())
01077       Out << " exact";
01078   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
01079     if (GEP->isInBounds())
01080       Out << " inbounds";
01081   }
01082 }
01083 
01084 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
01085                                   TypePrinting &TypePrinter,
01086                                   SlotTracker *Machine,
01087                                   const Module *Context) {
01088   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
01089     if (CI->getType()->isIntegerTy(1)) {
01090       Out << (CI->getZExtValue() ? "true" : "false");
01091       return;
01092     }
01093     Out << CI->getValue();
01094     return;
01095   }
01096 
01097   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
01098     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
01099         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
01100       // We would like to output the FP constant value in exponential notation,
01101       // but we cannot do this if doing so will lose precision.  Check here to
01102       // make sure that we only output it in exponential format if we can parse
01103       // the value back and get the same value.
01104       //
01105       bool ignored;
01106       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
01107       bool isInf = CFP->getValueAPF().isInfinity();
01108       bool isNaN = CFP->getValueAPF().isNaN();
01109       if (!isInf && !isNaN) {
01110         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
01111                                 CFP->getValueAPF().convertToFloat();
01112         SmallString<128> StrVal;
01113         raw_svector_ostream(StrVal) << Val;
01114 
01115         // Check to make sure that the stringized number is not some string like
01116         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
01117         // that the string matches the "[-+]?[0-9]" regex.
01118         //
01119         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
01120             ((StrVal[0] == '-' || StrVal[0] == '+') &&
01121              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
01122           // Reparse stringized version!
01123           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
01124             Out << StrVal;
01125             return;
01126           }
01127         }
01128       }
01129       // Otherwise we could not reparse it to exactly the same value, so we must
01130       // output the string in hexadecimal format!  Note that loading and storing
01131       // floating point types changes the bits of NaNs on some hosts, notably
01132       // x86, so we must not use these types.
01133       static_assert(sizeof(double) == sizeof(uint64_t),
01134                     "assuming that double is 64 bits!");
01135       APFloat apf = CFP->getValueAPF();
01136       // Floats are represented in ASCII IR as double, convert.
01137       if (!isDouble)
01138         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
01139                           &ignored);
01140       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
01141       return;
01142     }
01143 
01144     // Either half, or some form of long double.
01145     // These appear as a magic letter identifying the type, then a
01146     // fixed number of hex digits.
01147     Out << "0x";
01148     APInt API = CFP->getValueAPF().bitcastToAPInt();
01149     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
01150       Out << 'K';
01151       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
01152                                   /*Upper=*/true);
01153       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
01154                                   /*Upper=*/true);
01155       return;
01156     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
01157       Out << 'L';
01158       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
01159                                   /*Upper=*/true);
01160       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
01161                                   /*Upper=*/true);
01162     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
01163       Out << 'M';
01164       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
01165                                   /*Upper=*/true);
01166       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
01167                                   /*Upper=*/true);
01168     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
01169       Out << 'H';
01170       Out << format_hex_no_prefix(API.getZExtValue(), 4,
01171                                   /*Upper=*/true);
01172     } else
01173       llvm_unreachable("Unsupported floating point type");
01174     return;
01175   }
01176 
01177   if (isa<ConstantAggregateZero>(CV)) {
01178     Out << "zeroinitializer";
01179     return;
01180   }
01181 
01182   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
01183     Out << "blockaddress(";
01184     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
01185                            Context);
01186     Out << ", ";
01187     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
01188                            Context);
01189     Out << ")";
01190     return;
01191   }
01192 
01193   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
01194     Type *ETy = CA->getType()->getElementType();
01195     Out << '[';
01196     TypePrinter.print(ETy, Out);
01197     Out << ' ';
01198     WriteAsOperandInternal(Out, CA->getOperand(0),
01199                            &TypePrinter, Machine,
01200                            Context);
01201     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01202       Out << ", ";
01203       TypePrinter.print(ETy, Out);
01204       Out << ' ';
01205       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
01206                              Context);
01207     }
01208     Out << ']';
01209     return;
01210   }
01211 
01212   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
01213     // As a special case, print the array as a string if it is an array of
01214     // i8 with ConstantInt values.
01215     if (CA->isString()) {
01216       Out << "c\"";
01217       PrintEscapedString(CA->getAsString(), Out);
01218       Out << '"';
01219       return;
01220     }
01221 
01222     Type *ETy = CA->getType()->getElementType();
01223     Out << '[';
01224     TypePrinter.print(ETy, Out);
01225     Out << ' ';
01226     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
01227                            &TypePrinter, Machine,
01228                            Context);
01229     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
01230       Out << ", ";
01231       TypePrinter.print(ETy, Out);
01232       Out << ' ';
01233       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
01234                              Machine, Context);
01235     }
01236     Out << ']';
01237     return;
01238   }
01239 
01240 
01241   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
01242     if (CS->getType()->isPacked())
01243       Out << '<';
01244     Out << '{';
01245     unsigned N = CS->getNumOperands();
01246     if (N) {
01247       Out << ' ';
01248       TypePrinter.print(CS->getOperand(0)->getType(), Out);
01249       Out << ' ';
01250 
01251       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
01252                              Context);
01253 
01254       for (unsigned i = 1; i < N; i++) {
01255         Out << ", ";
01256         TypePrinter.print(CS->getOperand(i)->getType(), Out);
01257         Out << ' ';
01258 
01259         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
01260                                Context);
01261       }
01262       Out << ' ';
01263     }
01264 
01265     Out << '}';
01266     if (CS->getType()->isPacked())
01267       Out << '>';
01268     return;
01269   }
01270 
01271   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
01272     Type *ETy = CV->getType()->getVectorElementType();
01273     Out << '<';
01274     TypePrinter.print(ETy, Out);
01275     Out << ' ';
01276     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
01277                            Machine, Context);
01278     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
01279       Out << ", ";
01280       TypePrinter.print(ETy, Out);
01281       Out << ' ';
01282       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
01283                              Machine, Context);
01284     }
01285     Out << '>';
01286     return;
01287   }
01288 
01289   if (isa<ConstantPointerNull>(CV)) {
01290     Out << "null";
01291     return;
01292   }
01293 
01294   if (isa<ConstantTokenNone>(CV)) {
01295     Out << "none";
01296     return;
01297   }
01298 
01299   if (isa<UndefValue>(CV)) {
01300     Out << "undef";
01301     return;
01302   }
01303 
01304   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
01305     Out << CE->getOpcodeName();
01306     WriteOptimizationInfo(Out, CE);
01307     if (CE->isCompare())
01308       Out << ' ' << getPredicateText(CE->getPredicate());
01309     Out << " (";
01310 
01311     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
01312       TypePrinter.print(GEP->getSourceElementType(), Out);
01313       Out << ", ";
01314     }
01315 
01316     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
01317       TypePrinter.print((*OI)->getType(), Out);
01318       Out << ' ';
01319       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
01320       if (OI+1 != CE->op_end())
01321         Out << ", ";
01322     }
01323 
01324     if (CE->hasIndices()) {
01325       ArrayRef<unsigned> Indices = CE->getIndices();
01326       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
01327         Out << ", " << Indices[i];
01328     }
01329 
01330     if (CE->isCast()) {
01331       Out << " to ";
01332       TypePrinter.print(CE->getType(), Out);
01333     }
01334 
01335     Out << ')';
01336     return;
01337   }
01338 
01339   Out << "<placeholder or erroneous Constant>";
01340 }
01341 
01342 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
01343                          TypePrinting *TypePrinter, SlotTracker *Machine,
01344                          const Module *Context) {
01345   Out << "!{";
01346   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
01347     const Metadata *MD = Node->getOperand(mi);
01348     if (!MD)
01349       Out << "null";
01350     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
01351       Value *V = MDV->getValue();
01352       TypePrinter->print(V->getType(), Out);
01353       Out << ' ';
01354       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
01355     } else {
01356       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
01357     }
01358     if (mi + 1 != me)
01359       Out << ", ";
01360   }
01361 
01362   Out << "}";
01363 }
01364 
01365 namespace {
01366 struct FieldSeparator {
01367   bool Skip;
01368   const char *Sep;
01369   FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
01370 };
01371 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
01372   if (FS.Skip) {
01373     FS.Skip = false;
01374     return OS;
01375   }
01376   return OS << FS.Sep;
01377 }
01378 struct MDFieldPrinter {
01379   raw_ostream &Out;
01380   FieldSeparator FS;
01381   TypePrinting *TypePrinter;
01382   SlotTracker *Machine;
01383   const Module *Context;
01384 
01385   explicit MDFieldPrinter(raw_ostream &Out)
01386       : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
01387   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
01388                  SlotTracker *Machine, const Module *Context)
01389       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
01390   }
01391   void printTag(const DINode *N);
01392   void printMacinfoType(const DIMacroNode *N);
01393   void printString(StringRef Name, StringRef Value,
01394                    bool ShouldSkipEmpty = true);
01395   void printMetadata(StringRef Name, const Metadata *MD,
01396                      bool ShouldSkipNull = true);
01397   template <class IntTy>
01398   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
01399   void printBool(StringRef Name, bool Value);
01400   void printDIFlags(StringRef Name, unsigned Flags);
01401   template <class IntTy, class Stringifier>
01402   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
01403                       bool ShouldSkipZero = true);
01404 };
01405 } // end namespace
01406 
01407 void MDFieldPrinter::printTag(const DINode *N) {
01408   Out << FS << "tag: ";
01409   if (const char *Tag = dwarf::TagString(N->getTag()))
01410     Out << Tag;
01411   else
01412     Out << N->getTag();
01413 }
01414 
01415 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
01416   Out << FS << "type: ";
01417   if (const char *Type = dwarf::MacinfoString(N->getMacinfoType()))
01418     Out << Type;
01419   else
01420     Out << N->getMacinfoType();
01421 }
01422 
01423 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
01424                                  bool ShouldSkipEmpty) {
01425   if (ShouldSkipEmpty && Value.empty())
01426     return;
01427 
01428   Out << FS << Name << ": \"";
01429   PrintEscapedString(Value, Out);
01430   Out << "\"";
01431 }
01432 
01433 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
01434                                    TypePrinting *TypePrinter,
01435                                    SlotTracker *Machine,
01436                                    const Module *Context) {
01437   if (!MD) {
01438     Out << "null";
01439     return;
01440   }
01441   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
01442 }
01443 
01444 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
01445                                    bool ShouldSkipNull) {
01446   if (ShouldSkipNull && !MD)
01447     return;
01448 
01449   Out << FS << Name << ": ";
01450   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
01451 }
01452 
01453 template <class IntTy>
01454 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
01455   if (ShouldSkipZero && !Int)
01456     return;
01457 
01458   Out << FS << Name << ": " << Int;
01459 }
01460 
01461 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
01462   Out << FS << Name << ": " << (Value ? "true" : "false");
01463 }
01464 
01465 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
01466   if (!Flags)
01467     return;
01468 
01469   Out << FS << Name << ": ";
01470 
01471   SmallVector<unsigned, 8> SplitFlags;
01472   unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
01473 
01474   FieldSeparator FlagsFS(" | ");
01475   for (unsigned F : SplitFlags) {
01476     const char *StringF = DINode::getFlagString(F);
01477     assert(StringF && "Expected valid flag");
01478     Out << FlagsFS << StringF;
01479   }
01480   if (Extra || SplitFlags.empty())
01481     Out << FlagsFS << Extra;
01482 }
01483 
01484 template <class IntTy, class Stringifier>
01485 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
01486                                     Stringifier toString, bool ShouldSkipZero) {
01487   if (!Value)
01488     return;
01489 
01490   Out << FS << Name << ": ";
01491   if (const char *S = toString(Value))
01492     Out << S;
01493   else
01494     Out << Value;
01495 }
01496 
01497 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
01498                                TypePrinting *TypePrinter, SlotTracker *Machine,
01499                                const Module *Context) {
01500   Out << "!GenericDINode(";
01501   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01502   Printer.printTag(N);
01503   Printer.printString("header", N->getHeader());
01504   if (N->getNumDwarfOperands()) {
01505     Out << Printer.FS << "operands: {";
01506     FieldSeparator IFS;
01507     for (auto &I : N->dwarf_operands()) {
01508       Out << IFS;
01509       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
01510     }
01511     Out << "}";
01512   }
01513   Out << ")";
01514 }
01515 
01516 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
01517                             TypePrinting *TypePrinter, SlotTracker *Machine,
01518                             const Module *Context) {
01519   Out << "!DILocation(";
01520   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01521   // Always output the line, since 0 is a relevant and important value for it.
01522   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
01523   Printer.printInt("column", DL->getColumn());
01524   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
01525   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
01526   Out << ")";
01527 }
01528 
01529 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
01530                             TypePrinting *, SlotTracker *, const Module *) {
01531   Out << "!DISubrange(";
01532   MDFieldPrinter Printer(Out);
01533   Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
01534   Printer.printInt("lowerBound", N->getLowerBound());
01535   Out << ")";
01536 }
01537 
01538 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
01539                               TypePrinting *, SlotTracker *, const Module *) {
01540   Out << "!DIEnumerator(";
01541   MDFieldPrinter Printer(Out);
01542   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
01543   Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
01544   Out << ")";
01545 }
01546 
01547 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
01548                              TypePrinting *, SlotTracker *, const Module *) {
01549   Out << "!DIBasicType(";
01550   MDFieldPrinter Printer(Out);
01551   if (N->getTag() != dwarf::DW_TAG_base_type)
01552     Printer.printTag(N);
01553   Printer.printString("name", N->getName());
01554   Printer.printInt("size", N->getSizeInBits());
01555   Printer.printInt("align", N->getAlignInBits());
01556   Printer.printDwarfEnum("encoding", N->getEncoding(),
01557                          dwarf::AttributeEncodingString);
01558   Out << ")";
01559 }
01560 
01561 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
01562                                TypePrinting *TypePrinter, SlotTracker *Machine,
01563                                const Module *Context) {
01564   Out << "!DIDerivedType(";
01565   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01566   Printer.printTag(N);
01567   Printer.printString("name", N->getName());
01568   Printer.printMetadata("scope", N->getRawScope());
01569   Printer.printMetadata("file", N->getRawFile());
01570   Printer.printInt("line", N->getLine());
01571   Printer.printMetadata("baseType", N->getRawBaseType(),
01572                         /* ShouldSkipNull */ false);
01573   Printer.printInt("size", N->getSizeInBits());
01574   Printer.printInt("align", N->getAlignInBits());
01575   Printer.printInt("offset", N->getOffsetInBits());
01576   Printer.printDIFlags("flags", N->getFlags());
01577   Printer.printMetadata("extraData", N->getRawExtraData());
01578   Out << ")";
01579 }
01580 
01581 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
01582                                  TypePrinting *TypePrinter,
01583                                  SlotTracker *Machine, const Module *Context) {
01584   Out << "!DICompositeType(";
01585   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01586   Printer.printTag(N);
01587   Printer.printString("name", N->getName());
01588   Printer.printMetadata("scope", N->getRawScope());
01589   Printer.printMetadata("file", N->getRawFile());
01590   Printer.printInt("line", N->getLine());
01591   Printer.printMetadata("baseType", N->getRawBaseType());
01592   Printer.printInt("size", N->getSizeInBits());
01593   Printer.printInt("align", N->getAlignInBits());
01594   Printer.printInt("offset", N->getOffsetInBits());
01595   Printer.printDIFlags("flags", N->getFlags());
01596   Printer.printMetadata("elements", N->getRawElements());
01597   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
01598                          dwarf::LanguageString);
01599   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
01600   Printer.printMetadata("templateParams", N->getRawTemplateParams());
01601   Printer.printString("identifier", N->getIdentifier());
01602   Out << ")";
01603 }
01604 
01605 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
01606                                   TypePrinting *TypePrinter,
01607                                   SlotTracker *Machine, const Module *Context) {
01608   Out << "!DISubroutineType(";
01609   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01610   Printer.printDIFlags("flags", N->getFlags());
01611   Printer.printMetadata("types", N->getRawTypeArray(),
01612                         /* ShouldSkipNull */ false);
01613   Out << ")";
01614 }
01615 
01616 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
01617                         SlotTracker *, const Module *) {
01618   Out << "!DIFile(";
01619   MDFieldPrinter Printer(Out);
01620   Printer.printString("filename", N->getFilename(),
01621                       /* ShouldSkipEmpty */ false);
01622   Printer.printString("directory", N->getDirectory(),
01623                       /* ShouldSkipEmpty */ false);
01624   Out << ")";
01625 }
01626 
01627 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
01628                                TypePrinting *TypePrinter, SlotTracker *Machine,
01629                                const Module *Context) {
01630   Out << "!DICompileUnit(";
01631   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01632   Printer.printDwarfEnum("language", N->getSourceLanguage(),
01633                          dwarf::LanguageString, /* ShouldSkipZero */ false);
01634   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
01635   Printer.printString("producer", N->getProducer());
01636   Printer.printBool("isOptimized", N->isOptimized());
01637   Printer.printString("flags", N->getFlags());
01638   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
01639                    /* ShouldSkipZero */ false);
01640   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
01641   Printer.printInt("emissionKind", N->getEmissionKind(),
01642                    /* ShouldSkipZero */ false);
01643   Printer.printMetadata("enums", N->getRawEnumTypes());
01644   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
01645   Printer.printMetadata("subprograms", N->getRawSubprograms());
01646   Printer.printMetadata("globals", N->getRawGlobalVariables());
01647   Printer.printMetadata("imports", N->getRawImportedEntities());
01648   Printer.printMetadata("macros", N->getRawMacros());
01649   Printer.printInt("dwoId", N->getDWOId());
01650   Out << ")";
01651 }
01652 
01653 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
01654                               TypePrinting *TypePrinter, SlotTracker *Machine,
01655                               const Module *Context) {
01656   Out << "!DISubprogram(";
01657   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01658   Printer.printString("name", N->getName());
01659   Printer.printString("linkageName", N->getLinkageName());
01660   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01661   Printer.printMetadata("file", N->getRawFile());
01662   Printer.printInt("line", N->getLine());
01663   Printer.printMetadata("type", N->getRawType());
01664   Printer.printBool("isLocal", N->isLocalToUnit());
01665   Printer.printBool("isDefinition", N->isDefinition());
01666   Printer.printInt("scopeLine", N->getScopeLine());
01667   Printer.printMetadata("containingType", N->getRawContainingType());
01668   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
01669                          dwarf::VirtualityString);
01670   Printer.printInt("virtualIndex", N->getVirtualIndex());
01671   Printer.printDIFlags("flags", N->getFlags());
01672   Printer.printBool("isOptimized", N->isOptimized());
01673   Printer.printMetadata("templateParams", N->getRawTemplateParams());
01674   Printer.printMetadata("declaration", N->getRawDeclaration());
01675   Printer.printMetadata("variables", N->getRawVariables());
01676   Out << ")";
01677 }
01678 
01679 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
01680                                 TypePrinting *TypePrinter, SlotTracker *Machine,
01681                                 const Module *Context) {
01682   Out << "!DILexicalBlock(";
01683   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01684   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01685   Printer.printMetadata("file", N->getRawFile());
01686   Printer.printInt("line", N->getLine());
01687   Printer.printInt("column", N->getColumn());
01688   Out << ")";
01689 }
01690 
01691 static void writeDILexicalBlockFile(raw_ostream &Out,
01692                                     const DILexicalBlockFile *N,
01693                                     TypePrinting *TypePrinter,
01694                                     SlotTracker *Machine,
01695                                     const Module *Context) {
01696   Out << "!DILexicalBlockFile(";
01697   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01698   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01699   Printer.printMetadata("file", N->getRawFile());
01700   Printer.printInt("discriminator", N->getDiscriminator(),
01701                    /* ShouldSkipZero */ false);
01702   Out << ")";
01703 }
01704 
01705 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
01706                              TypePrinting *TypePrinter, SlotTracker *Machine,
01707                              const Module *Context) {
01708   Out << "!DINamespace(";
01709   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01710   Printer.printString("name", N->getName());
01711   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01712   Printer.printMetadata("file", N->getRawFile());
01713   Printer.printInt("line", N->getLine());
01714   Out << ")";
01715 }
01716 
01717 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
01718                          TypePrinting *TypePrinter, SlotTracker *Machine,
01719                          const Module *Context) {
01720   Out << "!DIMacro(";
01721   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01722   Printer.printMacinfoType(N);
01723   Printer.printInt("line", N->getLine());
01724   Printer.printString("name", N->getName());
01725   Printer.printString("value", N->getValue());
01726   Out << ")";
01727 }
01728 
01729 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
01730                              TypePrinting *TypePrinter, SlotTracker *Machine,
01731                              const Module *Context) {
01732   Out << "!DIMacroFile(";
01733   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01734   Printer.printInt("line", N->getLine());
01735   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
01736   Printer.printMetadata("nodes", N->getRawElements());
01737   Out << ")";
01738 }
01739 
01740 static void writeDIModule(raw_ostream &Out, const DIModule *N,
01741                           TypePrinting *TypePrinter, SlotTracker *Machine,
01742                           const Module *Context) {
01743   Out << "!DIModule(";
01744   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01745   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01746   Printer.printString("name", N->getName());
01747   Printer.printString("configMacros", N->getConfigurationMacros());
01748   Printer.printString("includePath", N->getIncludePath());
01749   Printer.printString("isysroot", N->getISysRoot());
01750   Out << ")";
01751 }
01752 
01753 
01754 static void writeDITemplateTypeParameter(raw_ostream &Out,
01755                                          const DITemplateTypeParameter *N,
01756                                          TypePrinting *TypePrinter,
01757                                          SlotTracker *Machine,
01758                                          const Module *Context) {
01759   Out << "!DITemplateTypeParameter(";
01760   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01761   Printer.printString("name", N->getName());
01762   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
01763   Out << ")";
01764 }
01765 
01766 static void writeDITemplateValueParameter(raw_ostream &Out,
01767                                           const DITemplateValueParameter *N,
01768                                           TypePrinting *TypePrinter,
01769                                           SlotTracker *Machine,
01770                                           const Module *Context) {
01771   Out << "!DITemplateValueParameter(";
01772   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01773   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
01774     Printer.printTag(N);
01775   Printer.printString("name", N->getName());
01776   Printer.printMetadata("type", N->getRawType());
01777   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
01778   Out << ")";
01779 }
01780 
01781 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
01782                                   TypePrinting *TypePrinter,
01783                                   SlotTracker *Machine, const Module *Context) {
01784   Out << "!DIGlobalVariable(";
01785   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01786   Printer.printString("name", N->getName());
01787   Printer.printString("linkageName", N->getLinkageName());
01788   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01789   Printer.printMetadata("file", N->getRawFile());
01790   Printer.printInt("line", N->getLine());
01791   Printer.printMetadata("type", N->getRawType());
01792   Printer.printBool("isLocal", N->isLocalToUnit());
01793   Printer.printBool("isDefinition", N->isDefinition());
01794   Printer.printMetadata("variable", N->getRawVariable());
01795   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
01796   Out << ")";
01797 }
01798 
01799 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
01800                                  TypePrinting *TypePrinter,
01801                                  SlotTracker *Machine, const Module *Context) {
01802   Out << "!DILocalVariable(";
01803   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01804   Printer.printString("name", N->getName());
01805   Printer.printInt("arg", N->getArg());
01806   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01807   Printer.printMetadata("file", N->getRawFile());
01808   Printer.printInt("line", N->getLine());
01809   Printer.printMetadata("type", N->getRawType());
01810   Printer.printDIFlags("flags", N->getFlags());
01811   Out << ")";
01812 }
01813 
01814 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
01815                               TypePrinting *TypePrinter, SlotTracker *Machine,
01816                               const Module *Context) {
01817   Out << "!DIExpression(";
01818   FieldSeparator FS;
01819   if (N->isValid()) {
01820     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
01821       const char *OpStr = dwarf::OperationEncodingString(I->getOp());
01822       assert(OpStr && "Expected valid opcode");
01823 
01824       Out << FS << OpStr;
01825       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
01826         Out << FS << I->getArg(A);
01827     }
01828   } else {
01829     for (const auto &I : N->getElements())
01830       Out << FS << I;
01831   }
01832   Out << ")";
01833 }
01834 
01835 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
01836                                 TypePrinting *TypePrinter, SlotTracker *Machine,
01837                                 const Module *Context) {
01838   Out << "!DIObjCProperty(";
01839   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01840   Printer.printString("name", N->getName());
01841   Printer.printMetadata("file", N->getRawFile());
01842   Printer.printInt("line", N->getLine());
01843   Printer.printString("setter", N->getSetterName());
01844   Printer.printString("getter", N->getGetterName());
01845   Printer.printInt("attributes", N->getAttributes());
01846   Printer.printMetadata("type", N->getRawType());
01847   Out << ")";
01848 }
01849 
01850 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
01851                                   TypePrinting *TypePrinter,
01852                                   SlotTracker *Machine, const Module *Context) {
01853   Out << "!DIImportedEntity(";
01854   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
01855   Printer.printTag(N);
01856   Printer.printString("name", N->getName());
01857   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
01858   Printer.printMetadata("entity", N->getRawEntity());
01859   Printer.printInt("line", N->getLine());
01860   Out << ")";
01861 }
01862 
01863 
01864 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
01865                                     TypePrinting *TypePrinter,
01866                                     SlotTracker *Machine,
01867                                     const Module *Context) {
01868   if (Node->isDistinct())
01869     Out << "distinct ";
01870   else if (Node->isTemporary())
01871     Out << "<temporary!> "; // Handle broken code.
01872 
01873   switch (Node->getMetadataID()) {
01874   default:
01875     llvm_unreachable("Expected uniquable MDNode");
01876 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
01877   case Metadata::CLASS##Kind:                                                  \
01878     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
01879     break;
01880 #include "llvm/IR/Metadata.def"
01881   }
01882 }
01883 
01884 // Full implementation of printing a Value as an operand with support for
01885 // TypePrinting, etc.
01886 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
01887                                    TypePrinting *TypePrinter,
01888                                    SlotTracker *Machine,
01889                                    const Module *Context) {
01890   if (V->hasName()) {
01891     PrintLLVMName(Out, V);
01892     return;
01893   }
01894 
01895   const Constant *CV = dyn_cast<Constant>(V);
01896   if (CV && !isa<GlobalValue>(CV)) {
01897     assert(TypePrinter && "Constants require TypePrinting!");
01898     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
01899     return;
01900   }
01901 
01902   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01903     Out << "asm ";
01904     if (IA->hasSideEffects())
01905       Out << "sideeffect ";
01906     if (IA->isAlignStack())
01907       Out << "alignstack ";
01908     // We don't emit the AD_ATT dialect as it's the assumed default.
01909     if (IA->getDialect() == InlineAsm::AD_Intel)
01910       Out << "inteldialect ";
01911     Out << '"';
01912     PrintEscapedString(IA->getAsmString(), Out);
01913     Out << "\", \"";
01914     PrintEscapedString(IA->getConstraintString(), Out);
01915     Out << '"';
01916     return;
01917   }
01918 
01919   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
01920     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
01921                            Context, /* FromValue */ true);
01922     return;
01923   }
01924 
01925   char Prefix = '%';
01926   int Slot;
01927   // If we have a SlotTracker, use it.
01928   if (Machine) {
01929     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01930       Slot = Machine->getGlobalSlot(GV);
01931       Prefix = '@';
01932     } else {
01933       Slot = Machine->getLocalSlot(V);
01934 
01935       // If the local value didn't succeed, then we may be referring to a value
01936       // from a different function.  Translate it, as this can happen when using
01937       // address of blocks.
01938       if (Slot == -1)
01939         if ((Machine = createSlotTracker(V))) {
01940           Slot = Machine->getLocalSlot(V);
01941           delete Machine;
01942         }
01943     }
01944   } else if ((Machine = createSlotTracker(V))) {
01945     // Otherwise, create one to get the # and then destroy it.
01946     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01947       Slot = Machine->getGlobalSlot(GV);
01948       Prefix = '@';
01949     } else {
01950       Slot = Machine->getLocalSlot(V);
01951     }
01952     delete Machine;
01953     Machine = nullptr;
01954   } else {
01955     Slot = -1;
01956   }
01957 
01958   if (Slot != -1)
01959     Out << Prefix << Slot;
01960   else
01961     Out << "<badref>";
01962 }
01963 
01964 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
01965                                    TypePrinting *TypePrinter,
01966                                    SlotTracker *Machine, const Module *Context,
01967                                    bool FromValue) {
01968   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
01969     std::unique_ptr<SlotTracker> MachineStorage;
01970     if (!Machine) {
01971       MachineStorage = make_unique<SlotTracker>(Context);
01972       Machine = MachineStorage.get();
01973     }
01974     int Slot = Machine->getMetadataSlot(N);
01975     if (Slot == -1)
01976       // Give the pointer value instead of "badref", since this comes up all
01977       // the time when debugging.
01978       Out << "<" << N << ">";
01979     else
01980       Out << '!' << Slot;
01981     return;
01982   }
01983 
01984   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
01985     Out << "!\"";
01986     PrintEscapedString(MDS->getString(), Out);
01987     Out << '"';
01988     return;
01989   }
01990 
01991   auto *V = cast<ValueAsMetadata>(MD);
01992   assert(TypePrinter && "TypePrinter required for metadata values");
01993   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
01994          "Unexpected function-local metadata outside of value argument");
01995 
01996   TypePrinter->print(V->getValue()->getType(), Out);
01997   Out << ' ';
01998   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
01999 }
02000 
02001 namespace {
02002 class AssemblyWriter {
02003   formatted_raw_ostream &Out;
02004   const Module *TheModule;
02005   std::unique_ptr<SlotTracker> SlotTrackerStorage;
02006   SlotTracker &Machine;
02007   TypePrinting TypePrinter;
02008   AssemblyAnnotationWriter *AnnotationWriter;
02009   SetVector<const Comdat *> Comdats;
02010   bool IsForDebug;
02011   bool ShouldPreserveUseListOrder;
02012   UseListOrderStack UseListOrders;
02013   SmallVector<StringRef, 8> MDNames;
02014 
02015 public:
02016   /// Construct an AssemblyWriter with an external SlotTracker
02017   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
02018                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
02019                  bool ShouldPreserveUseListOrder = false);
02020 
02021   void printMDNodeBody(const MDNode *MD);
02022   void printNamedMDNode(const NamedMDNode *NMD);
02023 
02024   void printModule(const Module *M);
02025 
02026   void writeOperand(const Value *Op, bool PrintType);
02027   void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
02028   void writeOperandBundles(ImmutableCallSite CS);
02029   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
02030   void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
02031                           AtomicOrdering FailureOrdering,
02032                           SynchronizationScope SynchScope);
02033 
02034   void writeAllMDNodes();
02035   void writeMDNode(unsigned Slot, const MDNode *Node);
02036   void writeAllAttributeGroups();
02037 
02038   void printTypeIdentities();
02039   void printGlobal(const GlobalVariable *GV);
02040   void printAlias(const GlobalAlias *GV);
02041   void printComdat(const Comdat *C);
02042   void printFunction(const Function *F);
02043   void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
02044   void printBasicBlock(const BasicBlock *BB);
02045   void printInstructionLine(const Instruction &I);
02046   void printInstruction(const Instruction &I);
02047 
02048   void printUseListOrder(const UseListOrder &Order);
02049   void printUseLists(const Function *F);
02050 
02051 private:
02052   /// \brief Print out metadata attachments.
02053   void printMetadataAttachments(
02054       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
02055       StringRef Separator);
02056 
02057   // printInfoComment - Print a little comment after the instruction indicating
02058   // which slot it occupies.
02059   void printInfoComment(const Value &V);
02060 
02061   // printGCRelocateComment - print comment after call to the gc.relocate
02062   // intrinsic indicating base and derived pointer names.
02063   void printGCRelocateComment(const GCRelocateInst &Relocate);
02064 };
02065 } // namespace
02066 
02067 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
02068                                const Module *M, AssemblyAnnotationWriter *AAW,
02069                                bool IsForDebug, bool ShouldPreserveUseListOrder)
02070     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
02071       IsForDebug(IsForDebug),
02072       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
02073   if (!TheModule)
02074     return;
02075   TypePrinter.incorporateTypes(*TheModule);
02076   for (const Function &F : *TheModule)
02077     if (const Comdat *C = F.getComdat())
02078       Comdats.insert(C);
02079   for (const GlobalVariable &GV : TheModule->globals())
02080     if (const Comdat *C = GV.getComdat())
02081       Comdats.insert(C);
02082 }
02083 
02084 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
02085   if (!Operand) {
02086     Out << "<null operand!>";
02087     return;
02088   }
02089   if (PrintType) {
02090     TypePrinter.print(Operand->getType(), Out);
02091     Out << ' ';
02092   }
02093   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
02094 }
02095 
02096 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
02097                                  SynchronizationScope SynchScope) {
02098   if (Ordering == NotAtomic)
02099     return;
02100 
02101   switch (SynchScope) {
02102   case SingleThread: Out << " singlethread"; break;
02103   case CrossThread: break;
02104   }
02105 
02106   switch (Ordering) {
02107   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
02108   case Unordered: Out << " unordered"; break;
02109   case Monotonic: Out << " monotonic"; break;
02110   case Acquire: Out << " acquire"; break;
02111   case Release: Out << " release"; break;
02112   case AcquireRelease: Out << " acq_rel"; break;
02113   case SequentiallyConsistent: Out << " seq_cst"; break;
02114   }
02115 }
02116 
02117 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
02118                                         AtomicOrdering FailureOrdering,
02119                                         SynchronizationScope SynchScope) {
02120   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
02121 
02122   switch (SynchScope) {
02123   case SingleThread: Out << " singlethread"; break;
02124   case CrossThread: break;
02125   }
02126 
02127   switch (SuccessOrdering) {
02128   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
02129   case Unordered: Out << " unordered"; break;
02130   case Monotonic: Out << " monotonic"; break;
02131   case Acquire: Out << " acquire"; break;
02132   case Release: Out << " release"; break;
02133   case AcquireRelease: Out << " acq_rel"; break;
02134   case SequentiallyConsistent: Out << " seq_cst"; break;
02135   }
02136 
02137   switch (FailureOrdering) {
02138   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
02139   case Unordered: Out << " unordered"; break;
02140   case Monotonic: Out << " monotonic"; break;
02141   case Acquire: Out << " acquire"; break;
02142   case Release: Out << " release"; break;
02143   case AcquireRelease: Out << " acq_rel"; break;
02144   case SequentiallyConsistent: Out << " seq_cst"; break;
02145   }
02146 }
02147 
02148 void AssemblyWriter::writeParamOperand(const Value *Operand,
02149                                        AttributeSet Attrs, unsigned Idx) {
02150   if (!Operand) {
02151     Out << "<null operand!>";
02152     return;
02153   }
02154 
02155   // Print the type
02156   TypePrinter.print(Operand->getType(), Out);
02157   // Print parameter attributes list
02158   if (Attrs.hasAttributes(Idx))
02159     Out << ' ' << Attrs.getAsString(Idx);
02160   Out << ' ';
02161   // Print the operand
02162   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
02163 }
02164 
02165 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
02166   if (!CS.hasOperandBundles())
02167     return;
02168 
02169   Out << " [ ";
02170 
02171   bool FirstBundle = true;
02172   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
02173     OperandBundleUse BU = CS.getOperandBundleAt(i);
02174 
02175     if (!FirstBundle)
02176       Out << ", ";
02177     FirstBundle = false;
02178 
02179     Out << '"';
02180     PrintEscapedString(BU.getTagName(), Out);
02181     Out << '"';
02182 
02183     Out << '(';
02184 
02185     bool FirstInput = true;
02186     for (const auto &Input : BU.Inputs) {
02187       if (!FirstInput)
02188         Out << ", ";
02189       FirstInput = false;
02190 
02191       TypePrinter.print(Input->getType(), Out);
02192       Out << " ";
02193       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
02194     }
02195 
02196     Out << ')';
02197   }
02198 
02199   Out << " ]";
02200 }
02201 
02202 void AssemblyWriter::printModule(const Module *M) {
02203   Machine.initialize();
02204 
02205   if (ShouldPreserveUseListOrder)
02206     UseListOrders = predictUseListOrder(M);
02207 
02208   if (!M->getModuleIdentifier().empty() &&
02209       // Don't print the ID if it will start a new line (which would
02210       // require a comment char before it).
02211       M->getModuleIdentifier().find('\n') == std::string::npos)
02212     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
02213 
02214   const std::string &DL = M->getDataLayoutStr();
02215   if (!DL.empty())
02216     Out << "target datalayout = \"" << DL << "\"\n";
02217   if (!M->getTargetTriple().empty())
02218     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
02219 
02220   if (!M->getModuleInlineAsm().empty()) {
02221     Out << '\n';
02222 
02223     // Split the string into lines, to make it easier to read the .ll file.
02224     StringRef Asm = M->getModuleInlineAsm();
02225     do {
02226       StringRef Front;
02227       std::tie(Front, Asm) = Asm.split('\n');
02228 
02229       // We found a newline, print the portion of the asm string from the
02230       // last newline up to this newline.
02231       Out << "module asm \"";
02232       PrintEscapedString(Front, Out);
02233       Out << "\"\n";
02234     } while (!Asm.empty());
02235   }
02236 
02237   printTypeIdentities();
02238 
02239   // Output all comdats.
02240   if (!Comdats.empty())
02241     Out << '\n';
02242   for (const Comdat *C : Comdats) {
02243     printComdat(C);
02244     if (C != Comdats.back())
02245       Out << '\n';
02246   }
02247 
02248   // Output all globals.
02249   if (!M->global_empty()) Out << '\n';
02250   for (const GlobalVariable &GV : M->globals()) {
02251     printGlobal(&GV); Out << '\n';
02252   }
02253 
02254   // Output all aliases.
02255   if (!M->alias_empty()) Out << "\n";
02256   for (const GlobalAlias &GA : M->aliases())
02257     printAlias(&GA);
02258 
02259   // Output global use-lists.
02260   printUseLists(nullptr);
02261 
02262   // Output all of the functions.
02263   for (const Function &F : *M)
02264     printFunction(&F);
02265   assert(UseListOrders.empty() && "All use-lists should have been consumed");
02266 
02267   // Output all attribute groups.
02268   if (!Machine.as_empty()) {
02269     Out << '\n';
02270     writeAllAttributeGroups();
02271   }
02272 
02273   // Output named metadata.
02274   if (!M->named_metadata_empty()) Out << '\n';
02275 
02276   for (const NamedMDNode &Node : M->named_metadata())
02277     printNamedMDNode(&Node);
02278 
02279   // Output metadata.
02280   if (!Machine.mdn_empty()) {
02281     Out << '\n';
02282     writeAllMDNodes();
02283   }
02284 }
02285 
02286 static void printMetadataIdentifier(StringRef Name,
02287                                     formatted_raw_ostream &Out) {
02288   if (Name.empty()) {
02289     Out << "<empty name> ";
02290   } else {
02291     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
02292         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
02293       Out << Name[0];
02294     else
02295       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
02296     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
02297       unsigned char C = Name[i];
02298       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
02299           C == '.' || C == '_')
02300         Out << C;
02301       else
02302         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
02303     }
02304   }
02305 }
02306 
02307 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
02308   Out << '!';
02309   printMetadataIdentifier(NMD->getName(), Out);
02310   Out << " = !{";
02311   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
02312     if (i)
02313       Out << ", ";
02314     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
02315     if (Slot == -1)
02316       Out << "<badref>";
02317     else
02318       Out << '!' << Slot;
02319   }
02320   Out << "}\n";
02321 }
02322 
02323 static void PrintLinkage(GlobalValue::LinkageTypes LT,
02324                          formatted_raw_ostream &Out) {
02325   switch (LT) {
02326   case GlobalValue::ExternalLinkage: break;
02327   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
02328   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
02329   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
02330   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
02331   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
02332   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
02333   case GlobalValue::CommonLinkage:        Out << "common ";         break;
02334   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
02335   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
02336   case GlobalValue::AvailableExternallyLinkage:
02337     Out << "available_externally ";
02338     break;
02339   }
02340 }
02341 
02342 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
02343                             formatted_raw_ostream &Out) {
02344   switch (Vis) {
02345   case GlobalValue::DefaultVisibility: break;
02346   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
02347   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
02348   }
02349 }
02350 
02351 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
02352                                  formatted_raw_ostream &Out) {
02353   switch (SCT) {
02354   case GlobalValue::DefaultStorageClass: break;
02355   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
02356   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
02357   }
02358 }
02359 
02360 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
02361                                   formatted_raw_ostream &Out) {
02362   switch (TLM) {
02363     case GlobalVariable::NotThreadLocal:
02364       break;
02365     case GlobalVariable::GeneralDynamicTLSModel:
02366       Out << "thread_local ";
02367       break;
02368     case GlobalVariable::LocalDynamicTLSModel:
02369       Out << "thread_local(localdynamic) ";
02370       break;
02371     case GlobalVariable::InitialExecTLSModel:
02372       Out << "thread_local(initialexec) ";
02373       break;
02374     case GlobalVariable::LocalExecTLSModel:
02375       Out << "thread_local(localexec) ";
02376       break;
02377   }
02378 }
02379 
02380 static void maybePrintComdat(formatted_raw_ostream &Out,
02381                              const GlobalObject &GO) {
02382   const Comdat *C = GO.getComdat();
02383   if (!C)
02384     return;
02385 
02386   if (isa<GlobalVariable>(GO))
02387     Out << ',';
02388   Out << " comdat";
02389 
02390   if (GO.getName() == C->getName())
02391     return;
02392 
02393   Out << '(';
02394   PrintLLVMName(Out, C->getName(), ComdatPrefix);
02395   Out << ')';
02396 }
02397 
02398 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
02399   if (GV->isMaterializable())
02400     Out << "; Materializable\n";
02401 
02402   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
02403   Out << " = ";
02404 
02405   if (!GV->hasInitializer() && GV->hasExternalLinkage())
02406     Out << "external ";
02407 
02408   PrintLinkage(GV->getLinkage(), Out);
02409   PrintVisibility(GV->getVisibility(), Out);
02410   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
02411   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
02412   if (GV->hasUnnamedAddr())
02413     Out << "unnamed_addr ";
02414 
02415   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
02416     Out << "addrspace(" << AddressSpace << ") ";
02417   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
02418   Out << (GV->isConstant() ? "constant " : "global ");
02419   TypePrinter.print(GV->getValueType(), Out);
02420 
02421   if (GV->hasInitializer()) {
02422     Out << ' ';
02423     writeOperand(GV->getInitializer(), false);
02424   }
02425 
02426   if (GV->hasSection()) {
02427     Out << ", section \"";
02428     PrintEscapedString(GV->getSection(), Out);
02429     Out << '"';
02430   }
02431   maybePrintComdat(Out, *GV);
02432   if (GV->getAlignment())
02433     Out << ", align " << GV->getAlignment();
02434 
02435   printInfoComment(*GV);
02436 }
02437 
02438 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
02439   if (GA->isMaterializable())
02440     Out << "; Materializable\n";
02441 
02442   WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
02443   Out << " = ";
02444 
02445   PrintLinkage(GA->getLinkage(), Out);
02446   PrintVisibility(GA->getVisibility(), Out);
02447   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
02448   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
02449   if (GA->hasUnnamedAddr())
02450     Out << "unnamed_addr ";
02451 
02452   Out << "alias ";
02453 
02454   TypePrinter.print(GA->getValueType(), Out);
02455 
02456   Out << ", ";
02457 
02458   const Constant *Aliasee = GA->getAliasee();
02459 
02460   if (!Aliasee) {
02461     TypePrinter.print(GA->getType(), Out);
02462     Out << " <<NULL ALIASEE>>";
02463   } else {
02464     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
02465   }
02466 
02467   printInfoComment(*GA);
02468   Out << '\n';
02469 }
02470 
02471 void AssemblyWriter::printComdat(const Comdat *C) {
02472   C->print(Out);
02473 }
02474 
02475 void AssemblyWriter::printTypeIdentities() {
02476   if (TypePrinter.NumberedTypes.empty() &&
02477       TypePrinter.NamedTypes.empty())
02478     return;
02479 
02480   Out << '\n';
02481 
02482   // We know all the numbers that each type is used and we know that it is a
02483   // dense assignment.  Convert the map to an index table.
02484   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
02485   for (DenseMap<StructType*, unsigned>::iterator I =
02486        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
02487        I != E; ++I) {
02488     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
02489     NumberedTypes[I->second] = I->first;
02490   }
02491 
02492   // Emit all numbered types.
02493   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
02494     Out << '%' << i << " = type ";
02495 
02496     // Make sure we print out at least one level of the type structure, so
02497     // that we do not get %2 = type %2
02498     TypePrinter.printStructBody(NumberedTypes[i], Out);
02499     Out << '\n';
02500   }
02501 
02502   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
02503     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
02504     Out << " = type ";
02505 
02506     // Make sure we print out at least one level of the type structure, so
02507     // that we do not get %FILE = type %FILE
02508     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
02509     Out << '\n';
02510   }
02511 }
02512 
02513 /// printFunction - Print all aspects of a function.
02514 ///
02515 void AssemblyWriter::printFunction(const Function *F) {
02516   // Print out the return type and name.
02517   Out << '\n';
02518 
02519   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
02520 
02521   if (F->isMaterializable())
02522     Out << "; Materializable\n";
02523 
02524   const AttributeSet &Attrs = F->getAttributes();
02525   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
02526     AttributeSet AS = Attrs.getFnAttributes();
02527     std::string AttrStr;
02528 
02529     unsigned Idx = 0;
02530     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
02531       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
02532         break;
02533 
02534     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
02535          I != E; ++I) {
02536       Attribute Attr = *I;
02537       if (!Attr.isStringAttribute()) {
02538         if (!AttrStr.empty()) AttrStr += ' ';
02539         AttrStr += Attr.getAsString();
02540       }
02541     }
02542 
02543     if (!AttrStr.empty())
02544       Out << "; Function Attrs: " << AttrStr << '\n';
02545   }
02546 
02547   if (F->isDeclaration())
02548     Out << "declare ";
02549   else
02550     Out << "define ";
02551 
02552   PrintLinkage(F->getLinkage(), Out);
02553   PrintVisibility(F->getVisibility(), Out);
02554   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
02555 
02556   // Print the calling convention.
02557   if (F->getCallingConv() != CallingConv::C) {
02558     PrintCallingConv(F->getCallingConv(), Out);
02559     Out << " ";
02560   }
02561 
02562   FunctionType *FT = F->getFunctionType();
02563   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
02564     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
02565   TypePrinter.print(F->getReturnType(), Out);
02566   Out << ' ';
02567   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
02568   Out << '(';
02569   Machine.incorporateFunction(F);
02570 
02571   // Loop over the arguments, printing them...
02572   if (F->isDeclaration() && !IsForDebug) {
02573     // We're only interested in the type here - don't print argument names.
02574     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
02575       // Insert commas as we go... the first arg doesn't get a comma
02576       if (I)
02577         Out << ", ";
02578       // Output type...
02579       TypePrinter.print(FT->getParamType(I), Out);
02580 
02581       if (Attrs.hasAttributes(I + 1))
02582         Out << ' ' << Attrs.getAsString(I + 1);
02583     }
02584   } else {
02585     // The arguments are meaningful here, print them in detail.
02586     unsigned Idx = 1;
02587     for (const Argument &Arg : F->args()) {
02588       // Insert commas as we go... the first arg doesn't get a comma
02589       if (Idx != 1)
02590         Out << ", ";
02591       printArgument(&Arg, Attrs, Idx++);
02592     }
02593   }
02594 
02595   // Finish printing arguments...
02596   if (FT->isVarArg()) {
02597     if (FT->getNumParams()) Out << ", ";
02598     Out << "...";  // Output varargs portion of signature!
02599   }
02600   Out << ')';
02601   if (F->hasUnnamedAddr())
02602     Out << " unnamed_addr";
02603   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
02604     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
02605   if (F->hasSection()) {
02606     Out << " section \"";
02607     PrintEscapedString(F->getSection(), Out);
02608     Out << '"';
02609   }
02610   maybePrintComdat(Out, *F);
02611   if (F->getAlignment())
02612     Out << " align " << F->getAlignment();
02613   if (F->hasGC())
02614     Out << " gc \"" << F->getGC() << '"';
02615   if (F->hasPrefixData()) {
02616     Out << " prefix ";
02617     writeOperand(F->getPrefixData(), true);
02618   }
02619   if (F->hasPrologueData()) {
02620     Out << " prologue ";
02621     writeOperand(F->getPrologueData(), true);
02622   }
02623   if (F->hasPersonalityFn()) {
02624     Out << " personality ";
02625     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
02626   }
02627 
02628   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
02629   F->getAllMetadata(MDs);
02630   printMetadataAttachments(MDs, " ");
02631 
02632   if (F->isDeclaration()) {
02633     Out << '\n';
02634   } else {
02635     Out << " {";
02636     // Output all of the function's basic blocks.
02637     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
02638       printBasicBlock(&*I);
02639 
02640     // Output the function's use-lists.
02641     printUseLists(F);
02642 
02643     Out << "}\n";
02644   }
02645 
02646   Machine.purgeFunction();
02647 }
02648 
02649 /// printArgument - This member is called for every argument that is passed into
02650 /// the function.  Simply print it out
02651 ///
02652 void AssemblyWriter::printArgument(const Argument *Arg,
02653                                    AttributeSet Attrs, unsigned Idx) {
02654   // Output type...
02655   TypePrinter.print(Arg->getType(), Out);
02656 
02657   // Output parameter attributes list
02658   if (Attrs.hasAttributes(Idx))
02659     Out << ' ' << Attrs.getAsString(Idx);
02660 
02661   // Output name, if available...
02662   if (Arg->hasName()) {
02663     Out << ' ';
02664     PrintLLVMName(Out, Arg);
02665   }
02666 }
02667 
02668 /// printBasicBlock - This member is called for each basic block in a method.
02669 ///
02670 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
02671   if (BB->hasName()) {              // Print out the label if it exists...
02672     Out << "\n";
02673     PrintLLVMName(Out, BB->getName(), LabelPrefix);
02674     Out << ':';
02675   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
02676     Out << "\n; <label>:";
02677     int Slot = Machine.getLocalSlot(BB);
02678     if (Slot != -1)
02679       Out << Slot;
02680     else
02681       Out << "<badref>";
02682   }
02683 
02684   if (!BB->getParent()) {
02685     Out.PadToColumn(50);
02686     Out << "; Error: Block without parent!";
02687   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
02688     // Output predecessors for the block.
02689     Out.PadToColumn(50);
02690     Out << ";";
02691     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
02692 
02693     if (PI == PE) {
02694       Out << " No predecessors!";
02695     } else {
02696       Out << " preds = ";
02697       writeOperand(*PI, false);
02698       for (++PI; PI != PE; ++PI) {
02699         Out << ", ";
02700         writeOperand(*PI, false);
02701       }
02702     }
02703   }
02704 
02705   Out << "\n";
02706 
02707   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
02708 
02709   // Output all of the instructions in the basic block...
02710   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
02711     printInstructionLine(*I);
02712   }
02713 
02714   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
02715 }
02716 
02717 /// printInstructionLine - Print an instruction and a newline character.
02718 void AssemblyWriter::printInstructionLine(const Instruction &I) {
02719   printInstruction(I);
02720   Out << '\n';
02721 }
02722 
02723 /// printGCRelocateComment - print comment after call to the gc.relocate
02724 /// intrinsic indicating base and derived pointer names.
02725 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
02726   Out << " ; (";
02727   writeOperand(Relocate.getBasePtr(), false);
02728   Out << ", ";
02729   writeOperand(Relocate.getDerivedPtr(), false);
02730   Out << ")";
02731 }
02732 
02733 /// printInfoComment - Print a little comment after the instruction indicating
02734 /// which slot it occupies.
02735 ///
02736 void AssemblyWriter::printInfoComment(const Value &V) {
02737   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
02738     printGCRelocateComment(*Relocate);
02739 
02740   if (AnnotationWriter)
02741     AnnotationWriter->printInfoComment(V, Out);
02742 }
02743 
02744 // This member is called for each Instruction in a function..
02745 void AssemblyWriter::printInstruction(const Instruction &I) {
02746   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
02747 
02748   // Print out indentation for an instruction.
02749   Out << "  ";
02750 
02751   // Print out name if it exists...
02752   if (I.hasName()) {
02753     PrintLLVMName(Out, &I);
02754     Out << " = ";
02755   } else if (!I.getType()->isVoidTy()) {
02756     // Print out the def slot taken.
02757     int SlotNum = Machine.getLocalSlot(&I);
02758     if (SlotNum == -1)
02759       Out << "<badref> = ";
02760     else
02761       Out << '%' << SlotNum << " = ";
02762   }
02763 
02764   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02765     if (CI->isMustTailCall())
02766       Out << "musttail ";
02767     else if (CI->isTailCall())
02768       Out << "tail ";
02769     else if (CI->isNoTailCall())
02770       Out << "notail ";
02771   }
02772 
02773   // Print out the opcode...
02774   Out << I.getOpcodeName();
02775 
02776   // If this is an atomic load or store, print out the atomic marker.
02777   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
02778       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
02779     Out << " atomic";
02780 
02781   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
02782     Out << " weak";
02783 
02784   // If this is a volatile operation, print out the volatile marker.
02785   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
02786       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
02787       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
02788       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
02789     Out << " volatile";
02790 
02791   // Print out optimization information.
02792   WriteOptimizationInfo(Out, &I);
02793 
02794   // Print out the compare instruction predicates
02795   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
02796     Out << ' ' << getPredicateText(CI->getPredicate());
02797 
02798   // Print out the atomicrmw operation
02799   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
02800     writeAtomicRMWOperation(Out, RMWI->getOperation());
02801 
02802   // Print out the type of the operands...
02803   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
02804 
02805   // Special case conditional branches to swizzle the condition out to the front
02806   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
02807     const BranchInst &BI(cast<BranchInst>(I));
02808     Out << ' ';
02809     writeOperand(BI.getCondition(), true);
02810     Out << ", ";
02811     writeOperand(BI.getSuccessor(0), true);
02812     Out << ", ";
02813     writeOperand(BI.getSuccessor(1), true);
02814 
02815   } else if (isa<SwitchInst>(I)) {
02816     const SwitchInst& SI(cast<SwitchInst>(I));
02817     // Special case switch instruction to get formatting nice and correct.
02818     Out << ' ';
02819     writeOperand(SI.getCondition(), true);
02820     Out << ", ";
02821     writeOperand(SI.getDefaultDest(), true);
02822     Out << " [";
02823     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
02824          i != e; ++i) {
02825       Out << "\n    ";
02826       writeOperand(i.getCaseValue(), true);
02827       Out << ", ";
02828       writeOperand(i.getCaseSuccessor(), true);
02829     }
02830     Out << "\n  ]";
02831   } else if (isa<IndirectBrInst>(I)) {
02832     // Special case indirectbr instruction to get formatting nice and correct.
02833     Out << ' ';
02834     writeOperand(Operand, true);
02835     Out << ", [";
02836 
02837     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
02838       if (i != 1)
02839         Out << ", ";
02840       writeOperand(I.getOperand(i), true);
02841     }
02842     Out << ']';
02843   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
02844     Out << ' ';
02845     TypePrinter.print(I.getType(), Out);
02846     Out << ' ';
02847 
02848     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
02849       if (op) Out << ", ";
02850       Out << "[ ";
02851       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
02852       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
02853     }
02854   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
02855     Out << ' ';
02856     writeOperand(I.getOperand(0), true);
02857     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
02858       Out << ", " << *i;
02859   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
02860     Out << ' ';
02861     writeOperand(I.getOperand(0), true); Out << ", ";
02862     writeOperand(I.getOperand(1), true);
02863     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
02864       Out << ", " << *i;
02865   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
02866     Out << ' ';
02867     TypePrinter.print(I.getType(), Out);
02868     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
02869       Out << '\n';
02870 
02871     if (LPI->isCleanup())
02872       Out << "          cleanup";
02873 
02874     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
02875       if (i != 0 || LPI->isCleanup()) Out << "\n";
02876       if (LPI->isCatch(i))
02877         Out << "          catch ";
02878       else
02879         Out << "          filter ";
02880 
02881       writeOperand(LPI->getClause(i), true);
02882     }
02883   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
02884     Out << " within ";
02885     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
02886     Out << " [";
02887     unsigned Op = 0;
02888     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
02889       if (Op > 0)
02890         Out << ", ";
02891       writeOperand(PadBB, /*PrintType=*/true);
02892       ++Op;
02893     }
02894     Out << "] unwind ";
02895     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
02896       writeOperand(UnwindDest, /*PrintType=*/true);
02897     else
02898       Out << "to caller";
02899   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
02900     Out << " within ";
02901     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
02902     Out << " [";
02903     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
02904          ++Op) {
02905       if (Op > 0)
02906         Out << ", ";
02907       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
02908     }
02909     Out << ']';
02910   } else if (isa<ReturnInst>(I) && !Operand) {
02911     Out << " void";
02912   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
02913     Out << " from ";
02914     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
02915 
02916     Out << " to ";
02917     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
02918   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
02919     Out << " from ";
02920     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
02921 
02922     Out << " unwind ";
02923     if (CRI->hasUnwindDest())
02924       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
02925     else
02926       Out << "to caller";
02927   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02928     // Print the calling convention being used.
02929     if (CI->getCallingConv() != CallingConv::C) {
02930       Out << " ";
02931       PrintCallingConv(CI->getCallingConv(), Out);
02932     }
02933 
02934     Operand = CI->getCalledValue();
02935     FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
02936     Type *RetTy = FTy->getReturnType();
02937     const AttributeSet &PAL = CI->getAttributes();
02938 
02939     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02940       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02941 
02942     // If possible, print out the short form of the call instruction.  We can
02943     // only do this if the first argument is a pointer to a nonvararg function,
02944     // and if the return type is not a pointer to a function.
02945     //
02946     Out << ' ';
02947     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
02948     Out << ' ';
02949     writeOperand(Operand, false);
02950     Out << '(';
02951     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
02952       if (op > 0)
02953         Out << ", ";
02954       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
02955     }
02956 
02957     // Emit an ellipsis if this is a musttail call in a vararg function.  This
02958     // is only to aid readability, musttail calls forward varargs by default.
02959     if (CI->isMustTailCall() && CI->getParent() &&
02960         CI->getParent()->getParent() &&
02961         CI->getParent()->getParent()->isVarArg())
02962       Out << ", ...";
02963 
02964     Out << ')';
02965     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02966       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02967 
02968     writeOperandBundles(CI);
02969 
02970   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
02971     Operand = II->getCalledValue();
02972     FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
02973     Type *RetTy = FTy->getReturnType();
02974     const AttributeSet &PAL = II->getAttributes();
02975 
02976     // Print the calling convention being used.
02977     if (II->getCallingConv() != CallingConv::C) {
02978       Out << " ";
02979       PrintCallingConv(II->getCallingConv(), Out);
02980     }
02981 
02982     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02983       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02984 
02985     // If possible, print out the short form of the invoke instruction. We can
02986     // only do this if the first argument is a pointer to a nonvararg function,
02987     // and if the return type is not a pointer to a function.
02988     //
02989     Out << ' ';
02990     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
02991     Out << ' ';
02992     writeOperand(Operand, false);
02993     Out << '(';
02994     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
02995       if (op)
02996         Out << ", ";
02997       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
02998     }
02999 
03000     Out << ')';
03001     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
03002       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
03003 
03004     writeOperandBundles(II);
03005 
03006     Out << "\n          to ";
03007     writeOperand(II->getNormalDest(), true);
03008     Out << " unwind ";
03009     writeOperand(II->getUnwindDest(), true);
03010 
03011   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
03012     Out << ' ';
03013     if (AI->isUsedWithInAlloca())
03014       Out << "inalloca ";
03015     TypePrinter.print(AI->getAllocatedType(), Out);
03016 
03017     // Explicitly write the array size if the code is broken, if it's an array
03018     // allocation, or if the type is not canonical for scalar allocations.  The
03019     // latter case prevents the type from mutating when round-tripping through
03020     // assembly.
03021     if (!AI->getArraySize() || AI->isArrayAllocation() ||
03022         !AI->getArraySize()->getType()->isIntegerTy(32)) {
03023       Out << ", ";
03024       writeOperand(AI->getArraySize(), true);
03025     }
03026     if (AI->getAlignment()) {
03027       Out << ", align " << AI->getAlignment();
03028     }
03029   } else if (isa<CastInst>(I)) {
03030     if (Operand) {
03031       Out << ' ';
03032       writeOperand(Operand, true);   // Work with broken code
03033     }
03034     Out << " to ";
03035     TypePrinter.print(I.getType(), Out);
03036   } else if (isa<VAArgInst>(I)) {
03037     if (Operand) {
03038       Out << ' ';
03039       writeOperand(Operand, true);   // Work with broken code
03040     }
03041     Out << ", ";
03042     TypePrinter.print(I.getType(), Out);
03043   } else if (Operand) {   // Print the normal way.
03044     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
03045       Out << ' ';
03046       TypePrinter.print(GEP->getSourceElementType(), Out);
03047       Out << ',';
03048     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
03049       Out << ' ';
03050       TypePrinter.print(LI->getType(), Out);
03051       Out << ',';
03052     }
03053 
03054     // PrintAllTypes - Instructions who have operands of all the same type
03055     // omit the type from all but the first operand.  If the instruction has
03056     // different type operands (for example br), then they are all printed.
03057     bool PrintAllTypes = false;
03058     Type *TheType = Operand->getType();
03059 
03060     // Select, Store and ShuffleVector always print all types.
03061     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
03062         || isa<ReturnInst>(I)) {
03063       PrintAllTypes = true;
03064     } else {
03065       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
03066         Operand = I.getOperand(i);
03067         // note that Operand shouldn't be null, but the test helps make dump()
03068         // more tolerant of malformed IR
03069         if (Operand && Operand->getType() != TheType) {
03070           PrintAllTypes = true;    // We have differing types!  Print them all!
03071           break;
03072         }
03073       }
03074     }
03075 
03076     if (!PrintAllTypes) {
03077       Out << ' ';
03078       TypePrinter.print(TheType, Out);
03079     }
03080 
03081     Out << ' ';
03082     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
03083       if (i) Out << ", ";
03084       writeOperand(I.getOperand(i), PrintAllTypes);
03085     }
03086   }
03087 
03088   // Print atomic ordering/alignment for memory operations
03089   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
03090     if (LI->isAtomic())
03091       writeAtomic(LI->getOrdering(), LI->getSynchScope());
03092     if (LI->getAlignment())
03093       Out << ", align " << LI->getAlignment();
03094   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
03095     if (SI->isAtomic())
03096       writeAtomic(SI->getOrdering(), SI->getSynchScope());
03097     if (SI->getAlignment())
03098       Out << ", align " << SI->getAlignment();
03099   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
03100     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
03101                        CXI->getSynchScope());
03102   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
03103     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
03104   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
03105     writeAtomic(FI->getOrdering(), FI->getSynchScope());
03106   }
03107 
03108   // Print Metadata info.
03109   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
03110   I.getAllMetadata(InstMD);
03111   printMetadataAttachments(InstMD, ", ");
03112 
03113   // Print a nice comment.
03114   printInfoComment(I);
03115 }
03116 
03117 void AssemblyWriter::printMetadataAttachments(
03118     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
03119     StringRef Separator) {
03120   if (MDs.empty())
03121     return;
03122 
03123   if (MDNames.empty())
03124     MDs[0].second->getContext().getMDKindNames(MDNames);
03125 
03126   for (const auto &I : MDs) {
03127     unsigned Kind = I.first;
03128     Out << Separator;
03129     if (Kind < MDNames.size()) {
03130       Out << "!";
03131       printMetadataIdentifier(MDNames[Kind], Out);
03132     } else
03133       Out << "!<unknown kind #" << Kind << ">";
03134     Out << ' ';
03135     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
03136   }
03137 }
03138 
03139 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
03140   Out << '!' << Slot << " = ";
03141   printMDNodeBody(Node);
03142   Out << "\n";
03143 }
03144 
03145 void AssemblyWriter::writeAllMDNodes() {
03146   SmallVector<const MDNode *, 16> Nodes;
03147   Nodes.resize(Machine.mdn_size());
03148   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
03149        I != E; ++I)
03150     Nodes[I->second] = cast<MDNode>(I->first);
03151 
03152   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
03153     writeMDNode(i, Nodes[i]);
03154   }
03155 }
03156 
03157 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
03158   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
03159 }
03160 
03161 void AssemblyWriter::writeAllAttributeGroups() {
03162   std::vector<std::pair<AttributeSet, unsigned> > asVec;
03163   asVec.resize(Machine.as_size());
03164 
03165   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
03166        I != E; ++I)
03167     asVec[I->second] = *I;
03168 
03169   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
03170          I = asVec.begin(), E = asVec.end(); I != E; ++I)
03171     Out << "attributes #" << I->second << " = { "
03172         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
03173 }
03174 
03175 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
03176   bool IsInFunction = Machine.getFunction();
03177   if (IsInFunction)
03178     Out << "  ";
03179 
03180   Out << "uselistorder";
03181   if (const BasicBlock *BB =
03182           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
03183     Out << "_bb ";
03184     writeOperand(BB->getParent(), false);
03185     Out << ", ";
03186     writeOperand(BB, false);
03187   } else {
03188     Out << " ";
03189     writeOperand(Order.V, true);
03190   }
03191   Out << ", { ";
03192 
03193   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
03194   Out << Order.Shuffle[0];
03195   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
03196     Out << ", " << Order.Shuffle[I];
03197   Out << " }\n";
03198 }
03199 
03200 void AssemblyWriter::printUseLists(const Function *F) {
03201   auto hasMore =
03202       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
03203   if (!hasMore())
03204     // Nothing to do.
03205     return;
03206 
03207   Out << "\n; uselistorder directives\n";
03208   while (hasMore()) {
03209     printUseListOrder(UseListOrders.back());
03210     UseListOrders.pop_back();
03211   }
03212 }
03213 
03214 //===----------------------------------------------------------------------===//
03215 //                       External Interface declarations
03216 //===----------------------------------------------------------------------===//
03217 
03218 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
03219                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
03220   SlotTracker SlotTable(this);
03221   formatted_raw_ostream OS(ROS);
03222   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
03223                    ShouldPreserveUseListOrder);
03224   W.printModule(this);
03225 }
03226 
03227 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
03228   SlotTracker SlotTable(getParent());
03229   formatted_raw_ostream OS(ROS);
03230   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
03231   W.printNamedMDNode(this);
03232 }
03233 
03234 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
03235   PrintLLVMName(ROS, getName(), ComdatPrefix);
03236   ROS << " = comdat ";
03237 
03238   switch (getSelectionKind()) {
03239   case Comdat::Any:
03240     ROS << "any";
03241     break;
03242   case Comdat::ExactMatch:
03243     ROS << "exactmatch";
03244     break;
03245   case Comdat::Largest:
03246     ROS << "largest";
03247     break;
03248   case Comdat::NoDuplicates:
03249     ROS << "noduplicates";
03250     break;
03251   case Comdat::SameSize:
03252     ROS << "samesize";
03253     break;
03254   }
03255 
03256   ROS << '\n';
03257 }
03258 
03259 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
03260   TypePrinting TP;
03261   TP.print(const_cast<Type*>(this), OS);
03262 
03263   // If the type is a named struct type, print the body as well.
03264   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
03265     if (!STy->isLiteral()) {
03266       OS << " = type ";
03267       TP.printStructBody(STy, OS);
03268     }
03269 }
03270 
03271 static bool isReferencingMDNode(const Instruction &I) {
03272   if (const auto *CI = dyn_cast<CallInst>(&I))
03273     if (Function *F = CI->getCalledFunction())
03274       if (F->isIntrinsic())
03275         for (auto &Op : I.operands())
03276           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
03277             if (isa<MDNode>(V->getMetadata()))
03278               return true;
03279   return false;
03280 }
03281 
03282 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
03283   bool ShouldInitializeAllMetadata = false;
03284   if (auto *I = dyn_cast<Instruction>(this))
03285     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
03286   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
03287     ShouldInitializeAllMetadata = true;
03288 
03289   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
03290   print(ROS, MST, IsForDebug);
03291 }
03292 
03293 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
03294                   bool IsForDebug) const {
03295   formatted_raw_ostream OS(ROS);
03296   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
03297   SlotTracker &SlotTable =
03298       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
03299   auto incorporateFunction = [&](const Function *F) {
03300     if (F)
03301       MST.incorporateFunction(*F);
03302   };
03303 
03304   if (const Instruction *I = dyn_cast<Instruction>(this)) {
03305     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
03306     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
03307     W.printInstruction(*I);
03308   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
03309     incorporateFunction(BB->getParent());
03310     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
03311     W.printBasicBlock(BB);
03312   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
03313     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
03314     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
03315       W.printGlobal(V);
03316     else if (const Function *F = dyn_cast<Function>(GV))
03317       W.printFunction(F);
03318     else
03319       W.printAlias(cast<GlobalAlias>(GV));
03320   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
03321     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
03322   } else if (const Constant *C = dyn_cast<Constant>(this)) {
03323     TypePrinting TypePrinter;
03324     TypePrinter.print(C->getType(), OS);
03325     OS << ' ';
03326     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
03327   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
03328     this->printAsOperand(OS, /* PrintType */ true, MST);
03329   } else {
03330     llvm_unreachable("Unknown value to print out!");
03331   }
03332 }
03333 
03334 /// Print without a type, skipping the TypePrinting object.
03335 ///
03336 /// \return \c true iff printing was successful.
03337 static bool printWithoutType(const Value &V, raw_ostream &O,
03338                              SlotTracker *Machine, const Module *M) {
03339   if (V.hasName() || isa<GlobalValue>(V) ||
03340       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
03341     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
03342     return true;
03343   }
03344   return false;
03345 }
03346 
03347 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
03348                                ModuleSlotTracker &MST) {
03349   TypePrinting TypePrinter;
03350   if (const Module *M = MST.getModule())
03351     TypePrinter.incorporateTypes(*M);
03352   if (PrintType) {
03353     TypePrinter.print(V.getType(), O);
03354     O << ' ';
03355   }
03356 
03357   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
03358                          MST.getModule());
03359 }
03360 
03361 void Value::printAsOperand(raw_ostream &O, bool PrintType,
03362                            const Module *M) const {
03363   if (!M)
03364     M = getModuleFromVal(this);
03365 
03366   if (!PrintType)
03367     if (printWithoutType(*this, O, nullptr, M))
03368       return;
03369 
03370   SlotTracker Machine(
03371       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
03372   ModuleSlotTracker MST(Machine, M);
03373   printAsOperandImpl(*this, O, PrintType, MST);
03374 }
03375 
03376 void Value::printAsOperand(raw_ostream &O, bool PrintType,
03377                            ModuleSlotTracker &MST) const {
03378   if (!PrintType)
03379     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
03380       return;
03381 
03382   printAsOperandImpl(*this, O, PrintType, MST);
03383 }
03384 
03385 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
03386                               ModuleSlotTracker &MST, const Module *M,
03387                               bool OnlyAsOperand) {
03388   formatted_raw_ostream OS(ROS);
03389 
03390   TypePrinting TypePrinter;
03391   if (M)
03392     TypePrinter.incorporateTypes(*M);
03393 
03394   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
03395                          /* FromValue */ true);
03396 
03397   auto *N = dyn_cast<MDNode>(&MD);
03398   if (OnlyAsOperand || !N)
03399     return;
03400 
03401   OS << " = ";
03402   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
03403 }
03404 
03405 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
03406   ModuleSlotTracker MST(M, isa<MDNode>(this));
03407   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
03408 }
03409 
03410 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
03411                               const Module *M) const {
03412   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
03413 }
03414 
03415 void Metadata::print(raw_ostream &OS, const Module *M,
03416                      bool /*IsForDebug*/) const {
03417   ModuleSlotTracker MST(M, isa<MDNode>(this));
03418   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
03419 }
03420 
03421 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
03422                      const Module *M, bool /*IsForDebug*/) const {
03423   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
03424 }
03425 
03426 // Value::dump - allow easy printing of Values from the debugger.
03427 LLVM_DUMP_METHOD
03428 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
03429 
03430 // Type::dump - allow easy printing of Types from the debugger.
03431 LLVM_DUMP_METHOD
03432 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
03433 
03434 // Module::dump() - Allow printing of Modules from the debugger.
03435 LLVM_DUMP_METHOD
03436 void Module::dump() const {
03437   print(dbgs(), nullptr,
03438         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
03439 }
03440 
03441 // \brief Allow printing of Comdats from the debugger.
03442 LLVM_DUMP_METHOD
03443 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
03444 
03445 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
03446 LLVM_DUMP_METHOD
03447 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
03448 
03449 LLVM_DUMP_METHOD
03450 void Metadata::dump() const { dump(nullptr); }
03451 
03452 LLVM_DUMP_METHOD
03453 void Metadata::dump(const Module *M) const {
03454   print(dbgs(), M, /*IsForDebug=*/true);
03455   dbgs() << '\n';
03456 }