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