LLVM API Documentation

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 "AsmWriter.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.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/TypeFinder.h"
00035 #include "llvm/IR/ValueSymbolTable.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/Dwarf.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/FormattedStream.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include <algorithm>
00042 #include <cctype>
00043 using namespace llvm;
00044 
00045 // Make virtual table appear in this compilation unit.
00046 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
00047 
00048 //===----------------------------------------------------------------------===//
00049 // Helper Functions
00050 //===----------------------------------------------------------------------===//
00051 
00052 namespace {
00053 struct OrderMap {
00054   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
00055 
00056   unsigned size() const { return IDs.size(); }
00057   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
00058   std::pair<unsigned, bool> lookup(const Value *V) const {
00059     return IDs.lookup(V);
00060   }
00061   void index(const Value *V) {
00062     // Explicitly sequence get-size and insert-value operations to avoid UB.
00063     unsigned ID = IDs.size() + 1;
00064     IDs[V].first = ID;
00065   }
00066 };
00067 }
00068 
00069 static void orderValue(const Value *V, OrderMap &OM) {
00070   if (OM.lookup(V).first)
00071     return;
00072 
00073   if (const Constant *C = dyn_cast<Constant>(V))
00074     if (C->getNumOperands() && !isa<GlobalValue>(C))
00075       for (const Value *Op : C->operands())
00076         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
00077           orderValue(Op, OM);
00078 
00079   // Note: we cannot cache this lookup above, since inserting into the map
00080   // changes the map's size, and thus affects the other IDs.
00081   OM.index(V);
00082 }
00083 
00084 static OrderMap orderModule(const Module *M) {
00085   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
00086   // and ValueEnumerator::incorporateFunction().
00087   OrderMap OM;
00088 
00089   for (const GlobalVariable &G : M->globals()) {
00090     if (G.hasInitializer())
00091       if (!isa<GlobalValue>(G.getInitializer()))
00092         orderValue(G.getInitializer(), OM);
00093     orderValue(&G, OM);
00094   }
00095   for (const GlobalAlias &A : M->aliases()) {
00096     if (!isa<GlobalValue>(A.getAliasee()))
00097       orderValue(A.getAliasee(), OM);
00098     orderValue(&A, OM);
00099   }
00100   for (const Function &F : *M) {
00101     if (F.hasPrefixData())
00102       if (!isa<GlobalValue>(F.getPrefixData()))
00103         orderValue(F.getPrefixData(), OM);
00104     orderValue(&F, OM);
00105 
00106     if (F.isDeclaration())
00107       continue;
00108 
00109     for (const Argument &A : F.args())
00110       orderValue(&A, OM);
00111     for (const BasicBlock &BB : F) {
00112       orderValue(&BB, OM);
00113       for (const Instruction &I : BB) {
00114         for (const Value *Op : I.operands())
00115           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
00116               isa<InlineAsm>(*Op))
00117             orderValue(Op, OM);
00118         orderValue(&I, OM);
00119       }
00120     }
00121   }
00122   return OM;
00123 }
00124 
00125 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
00126                                          unsigned ID, const OrderMap &OM,
00127                                          UseListOrderStack &Stack) {
00128   // Predict use-list order for this one.
00129   typedef std::pair<const Use *, unsigned> Entry;
00130   SmallVector<Entry, 64> List;
00131   for (const Use &U : V->uses())
00132     // Check if this user will be serialized.
00133     if (OM.lookup(U.getUser()).first)
00134       List.push_back(std::make_pair(&U, List.size()));
00135 
00136   if (List.size() < 2)
00137     // We may have lost some users.
00138     return;
00139 
00140   bool GetsReversed =
00141       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
00142   if (auto *BA = dyn_cast<BlockAddress>(V))
00143     ID = OM.lookup(BA->getBasicBlock()).first;
00144   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
00145     const Use *LU = L.first;
00146     const Use *RU = R.first;
00147     if (LU == RU)
00148       return false;
00149 
00150     auto LID = OM.lookup(LU->getUser()).first;
00151     auto RID = OM.lookup(RU->getUser()).first;
00152 
00153     // If ID is 4, then expect: 7 6 5 1 2 3.
00154     if (LID < RID) {
00155       if (GetsReversed)
00156         if (RID <= ID)
00157           return true;
00158       return false;
00159     }
00160     if (RID < LID) {
00161       if (GetsReversed)
00162         if (LID <= ID)
00163           return false;
00164       return true;
00165     }
00166 
00167     // LID and RID are equal, so we have different operands of the same user.
00168     // Assume operands are added in order for all instructions.
00169     if (GetsReversed)
00170       if (LID <= ID)
00171         return LU->getOperandNo() < RU->getOperandNo();
00172     return LU->getOperandNo() > RU->getOperandNo();
00173   });
00174 
00175   if (std::is_sorted(
00176           List.begin(), List.end(),
00177           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
00178     // Order is already correct.
00179     return;
00180 
00181   // Store the shuffle.
00182   Stack.emplace_back(V, F, List.size());
00183   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
00184   for (size_t I = 0, E = List.size(); I != E; ++I)
00185     Stack.back().Shuffle[I] = List[I].second;
00186 }
00187 
00188 static void predictValueUseListOrder(const Value *V, const Function *F,
00189                                      OrderMap &OM, UseListOrderStack &Stack) {
00190   auto &IDPair = OM[V];
00191   assert(IDPair.first && "Unmapped value");
00192   if (IDPair.second)
00193     // Already predicted.
00194     return;
00195 
00196   // Do the actual prediction.
00197   IDPair.second = true;
00198   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
00199     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
00200 
00201   // Recursive descent into constants.
00202   if (const Constant *C = dyn_cast<Constant>(V))
00203     if (C->getNumOperands()) // Visit GlobalValues.
00204       for (const Value *Op : C->operands())
00205         if (isa<Constant>(Op)) // Visit GlobalValues.
00206           predictValueUseListOrder(Op, F, OM, Stack);
00207 }
00208 
00209 static UseListOrderStack predictUseListOrder(const Module *M) {
00210   OrderMap OM = orderModule(M);
00211 
00212   // Use-list orders need to be serialized after all the users have been added
00213   // to a value, or else the shuffles will be incomplete.  Store them per
00214   // function in a stack.
00215   //
00216   // Aside from function order, the order of values doesn't matter much here.
00217   UseListOrderStack Stack;
00218 
00219   // We want to visit the functions backward now so we can list function-local
00220   // constants in the last Function they're used in.  Module-level constants
00221   // have already been visited above.
00222   for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
00223     const Function &F = *I;
00224     if (F.isDeclaration())
00225       continue;
00226     for (const BasicBlock &BB : F)
00227       predictValueUseListOrder(&BB, &F, OM, Stack);
00228     for (const Argument &A : F.args())
00229       predictValueUseListOrder(&A, &F, OM, Stack);
00230     for (const BasicBlock &BB : F)
00231       for (const Instruction &I : BB)
00232         for (const Value *Op : I.operands())
00233           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
00234             predictValueUseListOrder(Op, &F, OM, Stack);
00235     for (const BasicBlock &BB : F)
00236       for (const Instruction &I : BB)
00237         predictValueUseListOrder(&I, &F, OM, Stack);
00238   }
00239 
00240   // Visit globals last.
00241   for (const GlobalVariable &G : M->globals())
00242     predictValueUseListOrder(&G, nullptr, OM, Stack);
00243   for (const Function &F : *M)
00244     predictValueUseListOrder(&F, nullptr, OM, Stack);
00245   for (const GlobalAlias &A : M->aliases())
00246     predictValueUseListOrder(&A, nullptr, OM, Stack);
00247   for (const GlobalVariable &G : M->globals())
00248     if (G.hasInitializer())
00249       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
00250   for (const GlobalAlias &A : M->aliases())
00251     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
00252   for (const Function &F : *M)
00253     if (F.hasPrefixData())
00254       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
00255 
00256   return Stack;
00257 }
00258 
00259 static const Module *getModuleFromVal(const Value *V) {
00260   if (const Argument *MA = dyn_cast<Argument>(V))
00261     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
00262 
00263   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00264     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
00265 
00266   if (const Instruction *I = dyn_cast<Instruction>(V)) {
00267     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
00268     return M ? M->getParent() : nullptr;
00269   }
00270 
00271   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00272     return GV->getParent();
00273   return nullptr;
00274 }
00275 
00276 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
00277   switch (cc) {
00278   default:                         Out << "cc" << cc; break;
00279   case CallingConv::Fast:          Out << "fastcc"; break;
00280   case CallingConv::Cold:          Out << "coldcc"; break;
00281   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
00282   case CallingConv::AnyReg:        Out << "anyregcc"; break;
00283   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
00284   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
00285   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
00286   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
00287   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
00288   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
00289   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
00290   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
00291   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
00292   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
00293   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
00294   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
00295   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
00296   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
00297   case CallingConv::X86_64_Win64:  Out << "x86_64_win64cc"; break;
00298   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
00299   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
00300   }
00301 }
00302 
00303 // PrintEscapedString - Print each character of the specified string, escaping
00304 // it if it is not printable or if it is an escape char.
00305 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
00306   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00307     unsigned char C = Name[i];
00308     if (isprint(C) && C != '\\' && C != '"')
00309       Out << C;
00310     else
00311       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
00312   }
00313 }
00314 
00315 enum PrefixType {
00316   GlobalPrefix,
00317   ComdatPrefix,
00318   LabelPrefix,
00319   LocalPrefix,
00320   NoPrefix
00321 };
00322 
00323 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00324 /// prefixed with % (if the string only contains simple characters) or is
00325 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00326 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
00327   assert(!Name.empty() && "Cannot get empty name!");
00328   switch (Prefix) {
00329   case NoPrefix: break;
00330   case GlobalPrefix: OS << '@'; break;
00331   case ComdatPrefix: OS << '$'; break;
00332   case LabelPrefix:  break;
00333   case LocalPrefix:  OS << '%'; break;
00334   }
00335 
00336   // Scan the name to see if it needs quotes first.
00337   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
00338   if (!NeedsQuotes) {
00339     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
00340       // By making this unsigned, the value passed in to isalnum will always be
00341       // in the range 0-255.  This is important when building with MSVC because
00342       // its implementation will assert.  This situation can arise when dealing
00343       // with UTF-8 multibyte characters.
00344       unsigned char C = Name[i];
00345       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
00346           C != '_') {
00347         NeedsQuotes = true;
00348         break;
00349       }
00350     }
00351   }
00352 
00353   // If we didn't need any quotes, just write out the name in one blast.
00354   if (!NeedsQuotes) {
00355     OS << Name;
00356     return;
00357   }
00358 
00359   // Okay, we need quotes.  Output the quotes and escape any scary characters as
00360   // needed.
00361   OS << '"';
00362   PrintEscapedString(Name, OS);
00363   OS << '"';
00364 }
00365 
00366 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
00367 /// prefixed with % (if the string only contains simple characters) or is
00368 /// surrounded with ""'s (if it has special chars in it).  Print it out.
00369 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
00370   PrintLLVMName(OS, V->getName(),
00371                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
00372 }
00373 
00374 
00375 namespace llvm {
00376 
00377 void TypePrinting::incorporateTypes(const Module &M) {
00378   NamedTypes.run(M, false);
00379 
00380   // The list of struct types we got back includes all the struct types, split
00381   // the unnamed ones out to a numbering and remove the anonymous structs.
00382   unsigned NextNumber = 0;
00383 
00384   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
00385   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
00386     StructType *STy = *I;
00387 
00388     // Ignore anonymous types.
00389     if (STy->isLiteral())
00390       continue;
00391 
00392     if (STy->getName().empty())
00393       NumberedTypes[STy] = NextNumber++;
00394     else
00395       *NextToUse++ = STy;
00396   }
00397 
00398   NamedTypes.erase(NextToUse, NamedTypes.end());
00399 }
00400 
00401 
00402 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
00403 /// use of type names or up references to shorten the type name where possible.
00404 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
00405   switch (Ty->getTypeID()) {
00406   case Type::VoidTyID:      OS << "void"; return;
00407   case Type::HalfTyID:      OS << "half"; return;
00408   case Type::FloatTyID:     OS << "float"; return;
00409   case Type::DoubleTyID:    OS << "double"; return;
00410   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
00411   case Type::FP128TyID:     OS << "fp128"; return;
00412   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
00413   case Type::LabelTyID:     OS << "label"; return;
00414   case Type::MetadataTyID:  OS << "metadata"; return;
00415   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
00416   case Type::IntegerTyID:
00417     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
00418     return;
00419 
00420   case Type::FunctionTyID: {
00421     FunctionType *FTy = cast<FunctionType>(Ty);
00422     print(FTy->getReturnType(), OS);
00423     OS << " (";
00424     for (FunctionType::param_iterator I = FTy->param_begin(),
00425          E = FTy->param_end(); I != E; ++I) {
00426       if (I != FTy->param_begin())
00427         OS << ", ";
00428       print(*I, OS);
00429     }
00430     if (FTy->isVarArg()) {
00431       if (FTy->getNumParams()) OS << ", ";
00432       OS << "...";
00433     }
00434     OS << ')';
00435     return;
00436   }
00437   case Type::StructTyID: {
00438     StructType *STy = cast<StructType>(Ty);
00439 
00440     if (STy->isLiteral())
00441       return printStructBody(STy, OS);
00442 
00443     if (!STy->getName().empty())
00444       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
00445 
00446     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
00447     if (I != NumberedTypes.end())
00448       OS << '%' << I->second;
00449     else  // Not enumerated, print the hex address.
00450       OS << "%\"type " << STy << '\"';
00451     return;
00452   }
00453   case Type::PointerTyID: {
00454     PointerType *PTy = cast<PointerType>(Ty);
00455     print(PTy->getElementType(), OS);
00456     if (unsigned AddressSpace = PTy->getAddressSpace())
00457       OS << " addrspace(" << AddressSpace << ')';
00458     OS << '*';
00459     return;
00460   }
00461   case Type::ArrayTyID: {
00462     ArrayType *ATy = cast<ArrayType>(Ty);
00463     OS << '[' << ATy->getNumElements() << " x ";
00464     print(ATy->getElementType(), OS);
00465     OS << ']';
00466     return;
00467   }
00468   case Type::VectorTyID: {
00469     VectorType *PTy = cast<VectorType>(Ty);
00470     OS << "<" << PTy->getNumElements() << " x ";
00471     print(PTy->getElementType(), OS);
00472     OS << '>';
00473     return;
00474   }
00475   }
00476   llvm_unreachable("Invalid TypeID");
00477 }
00478 
00479 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
00480   if (STy->isOpaque()) {
00481     OS << "opaque";
00482     return;
00483   }
00484 
00485   if (STy->isPacked())
00486     OS << '<';
00487 
00488   if (STy->getNumElements() == 0) {
00489     OS << "{}";
00490   } else {
00491     StructType::element_iterator I = STy->element_begin();
00492     OS << "{ ";
00493     print(*I++, OS);
00494     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
00495       OS << ", ";
00496       print(*I, OS);
00497     }
00498 
00499     OS << " }";
00500   }
00501   if (STy->isPacked())
00502     OS << '>';
00503 }
00504 
00505 //===----------------------------------------------------------------------===//
00506 // SlotTracker Class: Enumerate slot numbers for unnamed values
00507 //===----------------------------------------------------------------------===//
00508 /// This class provides computation of slot numbers for LLVM Assembly writing.
00509 ///
00510 class SlotTracker {
00511 public:
00512   /// ValueMap - A mapping of Values to slot numbers.
00513   typedef DenseMap<const Value*, unsigned> ValueMap;
00514 
00515 private:
00516   /// TheModule - The module for which we are holding slot numbers.
00517   const Module* TheModule;
00518 
00519   /// TheFunction - The function for which we are holding slot numbers.
00520   const Function* TheFunction;
00521   bool FunctionProcessed;
00522 
00523   /// mMap - The slot map for the module level data.
00524   ValueMap mMap;
00525   unsigned mNext;
00526 
00527   /// fMap - The slot map for the function level data.
00528   ValueMap fMap;
00529   unsigned fNext;
00530 
00531   /// mdnMap - Map for MDNodes.
00532   DenseMap<const MDNode*, unsigned> mdnMap;
00533   unsigned mdnNext;
00534 
00535   /// asMap - The slot map for attribute sets.
00536   DenseMap<AttributeSet, unsigned> asMap;
00537   unsigned asNext;
00538 public:
00539   /// Construct from a module
00540   explicit SlotTracker(const Module *M);
00541   /// Construct from a function, starting out in incorp state.
00542   explicit SlotTracker(const Function *F);
00543 
00544   /// Return the slot number of the specified value in it's type
00545   /// plane.  If something is not in the SlotTracker, return -1.
00546   int getLocalSlot(const Value *V);
00547   int getGlobalSlot(const GlobalValue *V);
00548   int getMetadataSlot(const MDNode *N);
00549   int getAttributeGroupSlot(AttributeSet AS);
00550 
00551   /// If you'd like to deal with a function instead of just a module, use
00552   /// this method to get its data into the SlotTracker.
00553   void incorporateFunction(const Function *F) {
00554     TheFunction = F;
00555     FunctionProcessed = false;
00556   }
00557 
00558   const Function *getFunction() const { return TheFunction; }
00559 
00560   /// After calling incorporateFunction, use this method to remove the
00561   /// most recently incorporated function from the SlotTracker. This
00562   /// will reset the state of the machine back to just the module contents.
00563   void purgeFunction();
00564 
00565   /// MDNode map iterators.
00566   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
00567   mdn_iterator mdn_begin() { return mdnMap.begin(); }
00568   mdn_iterator mdn_end() { return mdnMap.end(); }
00569   unsigned mdn_size() const { return mdnMap.size(); }
00570   bool mdn_empty() const { return mdnMap.empty(); }
00571 
00572   /// AttributeSet map iterators.
00573   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
00574   as_iterator as_begin()   { return asMap.begin(); }
00575   as_iterator as_end()     { return asMap.end(); }
00576   unsigned as_size() const { return asMap.size(); }
00577   bool as_empty() const    { return asMap.empty(); }
00578 
00579   /// This function does the actual initialization.
00580   inline void initialize();
00581 
00582   // Implementation Details
00583 private:
00584   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00585   void CreateModuleSlot(const GlobalValue *V);
00586 
00587   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
00588   void CreateMetadataSlot(const MDNode *N);
00589 
00590   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
00591   void CreateFunctionSlot(const Value *V);
00592 
00593   /// \brief Insert the specified AttributeSet into the slot table.
00594   void CreateAttributeSetSlot(AttributeSet AS);
00595 
00596   /// Add all of the module level global variables (and their initializers)
00597   /// and function declarations, but not the contents of those functions.
00598   void processModule();
00599 
00600   /// Add all of the functions arguments, basic blocks, and instructions.
00601   void processFunction();
00602 
00603   SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
00604   void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
00605 };
00606 
00607 SlotTracker *createSlotTracker(const Module *M) {
00608   return new SlotTracker(M);
00609 }
00610 
00611 static SlotTracker *createSlotTracker(const Value *V) {
00612   if (const Argument *FA = dyn_cast<Argument>(V))
00613     return new SlotTracker(FA->getParent());
00614 
00615   if (const Instruction *I = dyn_cast<Instruction>(V))
00616     if (I->getParent())
00617       return new SlotTracker(I->getParent()->getParent());
00618 
00619   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
00620     return new SlotTracker(BB->getParent());
00621 
00622   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00623     return new SlotTracker(GV->getParent());
00624 
00625   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00626     return new SlotTracker(GA->getParent());
00627 
00628   if (const Function *Func = dyn_cast<Function>(V))
00629     return new SlotTracker(Func);
00630 
00631   if (const MDNode *MD = dyn_cast<MDNode>(V)) {
00632     if (!MD->isFunctionLocal())
00633       return new SlotTracker(MD->getFunction());
00634 
00635     return new SlotTracker((Function *)nullptr);
00636   }
00637 
00638   return nullptr;
00639 }
00640 
00641 #if 0
00642 #define ST_DEBUG(X) dbgs() << X
00643 #else
00644 #define ST_DEBUG(X)
00645 #endif
00646 
00647 // Module level constructor. Causes the contents of the Module (sans functions)
00648 // to be added to the slot table.
00649 SlotTracker::SlotTracker(const Module *M)
00650   : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
00651     mNext(0), fNext(0),  mdnNext(0), asNext(0) {
00652 }
00653 
00654 // Function level constructor. Causes the contents of the Module and the one
00655 // function provided to be added to the slot table.
00656 SlotTracker::SlotTracker(const Function *F)
00657   : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
00658     FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
00659 }
00660 
00661 inline void SlotTracker::initialize() {
00662   if (TheModule) {
00663     processModule();
00664     TheModule = nullptr; ///< Prevent re-processing next time we're called.
00665   }
00666 
00667   if (TheFunction && !FunctionProcessed)
00668     processFunction();
00669 }
00670 
00671 // Iterate through all the global variables, functions, and global
00672 // variable initializers and create slots for them.
00673 void SlotTracker::processModule() {
00674   ST_DEBUG("begin processModule!\n");
00675 
00676   // Add all of the unnamed global variables to the value table.
00677   for (Module::const_global_iterator I = TheModule->global_begin(),
00678          E = TheModule->global_end(); I != E; ++I) {
00679     if (!I->hasName())
00680       CreateModuleSlot(I);
00681   }
00682 
00683   // Add metadata used by named metadata.
00684   for (Module::const_named_metadata_iterator
00685          I = TheModule->named_metadata_begin(),
00686          E = TheModule->named_metadata_end(); I != E; ++I) {
00687     const NamedMDNode *NMD = I;
00688     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
00689       CreateMetadataSlot(NMD->getOperand(i));
00690   }
00691 
00692   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
00693        I != E; ++I) {
00694     if (!I->hasName())
00695       // Add all the unnamed functions to the table.
00696       CreateModuleSlot(I);
00697 
00698     // Add all the function attributes to the table.
00699     // FIXME: Add attributes of other objects?
00700     AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
00701     if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
00702       CreateAttributeSetSlot(FnAttrs);
00703   }
00704 
00705   ST_DEBUG("end processModule!\n");
00706 }
00707 
00708 // Process the arguments, basic blocks, and instructions  of a function.
00709 void SlotTracker::processFunction() {
00710   ST_DEBUG("begin processFunction!\n");
00711   fNext = 0;
00712 
00713   // Add all the function arguments with no names.
00714   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
00715       AE = TheFunction->arg_end(); AI != AE; ++AI)
00716     if (!AI->hasName())
00717       CreateFunctionSlot(AI);
00718 
00719   ST_DEBUG("Inserting Instructions:\n");
00720 
00721   SmallVector<std::pair<unsigned, MDNode *>, 4> MDForInst;
00722 
00723   // Add all of the basic blocks and instructions with no names.
00724   for (Function::const_iterator BB = TheFunction->begin(),
00725        E = TheFunction->end(); BB != E; ++BB) {
00726     if (!BB->hasName())
00727       CreateFunctionSlot(BB);
00728 
00729     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
00730          ++I) {
00731       if (!I->getType()->isVoidTy() && !I->hasName())
00732         CreateFunctionSlot(I);
00733 
00734       // Intrinsics can directly use metadata.  We allow direct calls to any
00735       // llvm.foo function here, because the target may not be linked into the
00736       // optimizer.
00737       if (const CallInst *CI = dyn_cast<CallInst>(I)) {
00738         if (Function *F = CI->getCalledFunction())
00739           if (F->isIntrinsic())
00740             for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00741               if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
00742                 CreateMetadataSlot(N);
00743 
00744         // Add all the call attributes to the table.
00745         AttributeSet Attrs = CI->getAttributes().getFnAttributes();
00746         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00747           CreateAttributeSetSlot(Attrs);
00748       } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
00749         // Add all the call attributes to the table.
00750         AttributeSet Attrs = II->getAttributes().getFnAttributes();
00751         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
00752           CreateAttributeSetSlot(Attrs);
00753       }
00754 
00755       // Process metadata attached with this instruction.
00756       I->getAllMetadata(MDForInst);
00757       for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
00758         CreateMetadataSlot(MDForInst[i].second);
00759       MDForInst.clear();
00760     }
00761   }
00762 
00763   FunctionProcessed = true;
00764 
00765   ST_DEBUG("end processFunction!\n");
00766 }
00767 
00768 /// Clean up after incorporating a function. This is the only way to get out of
00769 /// the function incorporation state that affects get*Slot/Create*Slot. Function
00770 /// incorporation state is indicated by TheFunction != 0.
00771 void SlotTracker::purgeFunction() {
00772   ST_DEBUG("begin purgeFunction!\n");
00773   fMap.clear(); // Simply discard the function level map
00774   TheFunction = nullptr;
00775   FunctionProcessed = false;
00776   ST_DEBUG("end purgeFunction!\n");
00777 }
00778 
00779 /// getGlobalSlot - Get the slot number of a global value.
00780 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
00781   // Check for uninitialized state and do lazy initialization.
00782   initialize();
00783 
00784   // Find the value in the module map
00785   ValueMap::iterator MI = mMap.find(V);
00786   return MI == mMap.end() ? -1 : (int)MI->second;
00787 }
00788 
00789 /// getMetadataSlot - Get the slot number of a MDNode.
00790 int SlotTracker::getMetadataSlot(const MDNode *N) {
00791   // Check for uninitialized state and do lazy initialization.
00792   initialize();
00793 
00794   // Find the MDNode in the module map
00795   mdn_iterator MI = mdnMap.find(N);
00796   return MI == mdnMap.end() ? -1 : (int)MI->second;
00797 }
00798 
00799 
00800 /// getLocalSlot - Get the slot number for a value that is local to a function.
00801 int SlotTracker::getLocalSlot(const Value *V) {
00802   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
00803 
00804   // Check for uninitialized state and do lazy initialization.
00805   initialize();
00806 
00807   ValueMap::iterator FI = fMap.find(V);
00808   return FI == fMap.end() ? -1 : (int)FI->second;
00809 }
00810 
00811 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
00812   // Check for uninitialized state and do lazy initialization.
00813   initialize();
00814 
00815   // Find the AttributeSet in the module map.
00816   as_iterator AI = asMap.find(AS);
00817   return AI == asMap.end() ? -1 : (int)AI->second;
00818 }
00819 
00820 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
00821 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
00822   assert(V && "Can't insert a null Value into SlotTracker!");
00823   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
00824   assert(!V->hasName() && "Doesn't need a slot!");
00825 
00826   unsigned DestSlot = mNext++;
00827   mMap[V] = DestSlot;
00828 
00829   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00830            DestSlot << " [");
00831   // G = Global, F = Function, A = Alias, o = other
00832   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
00833             (isa<Function>(V) ? 'F' :
00834              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
00835 }
00836 
00837 /// CreateSlot - Create a new slot for the specified value if it has no name.
00838 void SlotTracker::CreateFunctionSlot(const Value *V) {
00839   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
00840 
00841   unsigned DestSlot = fNext++;
00842   fMap[V] = DestSlot;
00843 
00844   // G = Global, F = Function, o = other
00845   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
00846            DestSlot << " [o]\n");
00847 }
00848 
00849 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
00850 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
00851   assert(N && "Can't insert a null Value into SlotTracker!");
00852 
00853   // Don't insert if N is a function-local metadata, these are always printed
00854   // inline.
00855   if (!N->isFunctionLocal()) {
00856     mdn_iterator I = mdnMap.find(N);
00857     if (I != mdnMap.end())
00858       return;
00859 
00860     unsigned DestSlot = mdnNext++;
00861     mdnMap[N] = DestSlot;
00862   }
00863 
00864   // Recursively add any MDNodes referenced by operands.
00865   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00866     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
00867       CreateMetadataSlot(Op);
00868 }
00869 
00870 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
00871   assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
00872          "Doesn't need a slot!");
00873 
00874   as_iterator I = asMap.find(AS);
00875   if (I != asMap.end())
00876     return;
00877 
00878   unsigned DestSlot = asNext++;
00879   asMap[AS] = DestSlot;
00880 }
00881 
00882 //===----------------------------------------------------------------------===//
00883 // AsmWriter Implementation
00884 //===----------------------------------------------------------------------===//
00885 
00886 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
00887                                    TypePrinting *TypePrinter,
00888                                    SlotTracker *Machine,
00889                                    const Module *Context);
00890 
00891 static const char *getPredicateText(unsigned predicate) {
00892   const char * pred = "unknown";
00893   switch (predicate) {
00894   case FCmpInst::FCMP_FALSE: pred = "false"; break;
00895   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
00896   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
00897   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
00898   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
00899   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
00900   case FCmpInst::FCMP_ONE:   pred = "one"; break;
00901   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
00902   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
00903   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
00904   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
00905   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
00906   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
00907   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
00908   case FCmpInst::FCMP_UNE:   pred = "une"; break;
00909   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
00910   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
00911   case ICmpInst::ICMP_NE:    pred = "ne"; break;
00912   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
00913   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
00914   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
00915   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
00916   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
00917   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
00918   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
00919   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
00920   }
00921   return pred;
00922 }
00923 
00924 static void writeAtomicRMWOperation(raw_ostream &Out,
00925                                     AtomicRMWInst::BinOp Op) {
00926   switch (Op) {
00927   default: Out << " <unknown operation " << Op << ">"; break;
00928   case AtomicRMWInst::Xchg: Out << " xchg"; break;
00929   case AtomicRMWInst::Add:  Out << " add"; break;
00930   case AtomicRMWInst::Sub:  Out << " sub"; break;
00931   case AtomicRMWInst::And:  Out << " and"; break;
00932   case AtomicRMWInst::Nand: Out << " nand"; break;
00933   case AtomicRMWInst::Or:   Out << " or"; break;
00934   case AtomicRMWInst::Xor:  Out << " xor"; break;
00935   case AtomicRMWInst::Max:  Out << " max"; break;
00936   case AtomicRMWInst::Min:  Out << " min"; break;
00937   case AtomicRMWInst::UMax: Out << " umax"; break;
00938   case AtomicRMWInst::UMin: Out << " umin"; break;
00939   }
00940 }
00941 
00942 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
00943   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
00944     // Unsafe algebra implies all the others, no need to write them all out
00945     if (FPO->hasUnsafeAlgebra())
00946       Out << " fast";
00947     else {
00948       if (FPO->hasNoNaNs())
00949         Out << " nnan";
00950       if (FPO->hasNoInfs())
00951         Out << " ninf";
00952       if (FPO->hasNoSignedZeros())
00953         Out << " nsz";
00954       if (FPO->hasAllowReciprocal())
00955         Out << " arcp";
00956     }
00957   }
00958 
00959   if (const OverflowingBinaryOperator *OBO =
00960         dyn_cast<OverflowingBinaryOperator>(U)) {
00961     if (OBO->hasNoUnsignedWrap())
00962       Out << " nuw";
00963     if (OBO->hasNoSignedWrap())
00964       Out << " nsw";
00965   } else if (const PossiblyExactOperator *Div =
00966                dyn_cast<PossiblyExactOperator>(U)) {
00967     if (Div->isExact())
00968       Out << " exact";
00969   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
00970     if (GEP->isInBounds())
00971       Out << " inbounds";
00972   }
00973 }
00974 
00975 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
00976                                   TypePrinting &TypePrinter,
00977                                   SlotTracker *Machine,
00978                                   const Module *Context) {
00979   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00980     if (CI->getType()->isIntegerTy(1)) {
00981       Out << (CI->getZExtValue() ? "true" : "false");
00982       return;
00983     }
00984     Out << CI->getValue();
00985     return;
00986   }
00987 
00988   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00989     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
00990         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
00991       // We would like to output the FP constant value in exponential notation,
00992       // but we cannot do this if doing so will lose precision.  Check here to
00993       // make sure that we only output it in exponential format if we can parse
00994       // the value back and get the same value.
00995       //
00996       bool ignored;
00997       bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
00998       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
00999       bool isInf = CFP->getValueAPF().isInfinity();
01000       bool isNaN = CFP->getValueAPF().isNaN();
01001       if (!isHalf && !isInf && !isNaN) {
01002         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
01003                                 CFP->getValueAPF().convertToFloat();
01004         SmallString<128> StrVal;
01005         raw_svector_ostream(StrVal) << Val;
01006 
01007         // Check to make sure that the stringized number is not some string like
01008         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
01009         // that the string matches the "[-+]?[0-9]" regex.
01010         //
01011         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
01012             ((StrVal[0] == '-' || StrVal[0] == '+') &&
01013              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
01014           // Reparse stringized version!
01015           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
01016             Out << StrVal.str();
01017             return;
01018           }
01019         }
01020       }
01021       // Otherwise we could not reparse it to exactly the same value, so we must
01022       // output the string in hexadecimal format!  Note that loading and storing
01023       // floating point types changes the bits of NaNs on some hosts, notably
01024       // x86, so we must not use these types.
01025       static_assert(sizeof(double) == sizeof(uint64_t),
01026                     "assuming that double is 64 bits!");
01027       char Buffer[40];
01028       APFloat apf = CFP->getValueAPF();
01029       // Halves and floats are represented in ASCII IR as double, convert.
01030       if (!isDouble)
01031         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
01032                           &ignored);
01033       Out << "0x" <<
01034               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
01035                             Buffer+40);
01036       return;
01037     }
01038 
01039     // Either half, or some form of long double.
01040     // These appear as a magic letter identifying the type, then a
01041     // fixed number of hex digits.
01042     Out << "0x";
01043     // Bit position, in the current word, of the next nibble to print.
01044     int shiftcount;
01045 
01046     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
01047       Out << 'K';
01048       // api needed to prevent premature destruction
01049       APInt api = CFP->getValueAPF().bitcastToAPInt();
01050       const uint64_t* p = api.getRawData();
01051       uint64_t word = p[1];
01052       shiftcount = 12;
01053       int width = api.getBitWidth();
01054       for (int j=0; j<width; j+=4, shiftcount-=4) {
01055         unsigned int nibble = (word>>shiftcount) & 15;
01056         if (nibble < 10)
01057           Out << (unsigned char)(nibble + '0');
01058         else
01059           Out << (unsigned char)(nibble - 10 + 'A');
01060         if (shiftcount == 0 && j+4 < width) {
01061           word = *p;
01062           shiftcount = 64;
01063           if (width-j-4 < 64)
01064             shiftcount = width-j-4;
01065         }
01066       }
01067       return;
01068     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
01069       shiftcount = 60;
01070       Out << 'L';
01071     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
01072       shiftcount = 60;
01073       Out << 'M';
01074     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
01075       shiftcount = 12;
01076       Out << 'H';
01077     } else
01078       llvm_unreachable("Unsupported floating point type");
01079     // api needed to prevent premature destruction
01080     APInt api = CFP->getValueAPF().bitcastToAPInt();
01081     const uint64_t* p = api.getRawData();
01082     uint64_t word = *p;
01083     int width = api.getBitWidth();
01084     for (int j=0; j<width; j+=4, shiftcount-=4) {
01085       unsigned int nibble = (word>>shiftcount) & 15;
01086       if (nibble < 10)
01087         Out << (unsigned char)(nibble + '0');
01088       else
01089         Out << (unsigned char)(nibble - 10 + 'A');
01090       if (shiftcount == 0 && j+4 < width) {
01091         word = *(++p);
01092         shiftcount = 64;
01093         if (width-j-4 < 64)
01094           shiftcount = width-j-4;
01095       }
01096     }
01097     return;
01098   }
01099 
01100   if (isa<ConstantAggregateZero>(CV)) {
01101     Out << "zeroinitializer";
01102     return;
01103   }
01104 
01105   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
01106     Out << "blockaddress(";
01107     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
01108                            Context);
01109     Out << ", ";
01110     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
01111                            Context);
01112     Out << ")";
01113     return;
01114   }
01115 
01116   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
01117     Type *ETy = CA->getType()->getElementType();
01118     Out << '[';
01119     TypePrinter.print(ETy, Out);
01120     Out << ' ';
01121     WriteAsOperandInternal(Out, CA->getOperand(0),
01122                            &TypePrinter, Machine,
01123                            Context);
01124     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01125       Out << ", ";
01126       TypePrinter.print(ETy, Out);
01127       Out << ' ';
01128       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
01129                              Context);
01130     }
01131     Out << ']';
01132     return;
01133   }
01134 
01135   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
01136     // As a special case, print the array as a string if it is an array of
01137     // i8 with ConstantInt values.
01138     if (CA->isString()) {
01139       Out << "c\"";
01140       PrintEscapedString(CA->getAsString(), Out);
01141       Out << '"';
01142       return;
01143     }
01144 
01145     Type *ETy = CA->getType()->getElementType();
01146     Out << '[';
01147     TypePrinter.print(ETy, Out);
01148     Out << ' ';
01149     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
01150                            &TypePrinter, Machine,
01151                            Context);
01152     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
01153       Out << ", ";
01154       TypePrinter.print(ETy, Out);
01155       Out << ' ';
01156       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
01157                              Machine, Context);
01158     }
01159     Out << ']';
01160     return;
01161   }
01162 
01163 
01164   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
01165     if (CS->getType()->isPacked())
01166       Out << '<';
01167     Out << '{';
01168     unsigned N = CS->getNumOperands();
01169     if (N) {
01170       Out << ' ';
01171       TypePrinter.print(CS->getOperand(0)->getType(), Out);
01172       Out << ' ';
01173 
01174       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
01175                              Context);
01176 
01177       for (unsigned i = 1; i < N; i++) {
01178         Out << ", ";
01179         TypePrinter.print(CS->getOperand(i)->getType(), Out);
01180         Out << ' ';
01181 
01182         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
01183                                Context);
01184       }
01185       Out << ' ';
01186     }
01187 
01188     Out << '}';
01189     if (CS->getType()->isPacked())
01190       Out << '>';
01191     return;
01192   }
01193 
01194   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
01195     Type *ETy = CV->getType()->getVectorElementType();
01196     Out << '<';
01197     TypePrinter.print(ETy, Out);
01198     Out << ' ';
01199     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
01200                            Machine, Context);
01201     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
01202       Out << ", ";
01203       TypePrinter.print(ETy, Out);
01204       Out << ' ';
01205       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
01206                              Machine, Context);
01207     }
01208     Out << '>';
01209     return;
01210   }
01211 
01212   if (isa<ConstantPointerNull>(CV)) {
01213     Out << "null";
01214     return;
01215   }
01216 
01217   if (isa<UndefValue>(CV)) {
01218     Out << "undef";
01219     return;
01220   }
01221 
01222   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
01223     Out << CE->getOpcodeName();
01224     WriteOptimizationInfo(Out, CE);
01225     if (CE->isCompare())
01226       Out << ' ' << getPredicateText(CE->getPredicate());
01227     Out << " (";
01228 
01229     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
01230       TypePrinter.print((*OI)->getType(), Out);
01231       Out << ' ';
01232       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
01233       if (OI+1 != CE->op_end())
01234         Out << ", ";
01235     }
01236 
01237     if (CE->hasIndices()) {
01238       ArrayRef<unsigned> Indices = CE->getIndices();
01239       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
01240         Out << ", " << Indices[i];
01241     }
01242 
01243     if (CE->isCast()) {
01244       Out << " to ";
01245       TypePrinter.print(CE->getType(), Out);
01246     }
01247 
01248     Out << ')';
01249     return;
01250   }
01251 
01252   Out << "<placeholder or erroneous Constant>";
01253 }
01254 
01255 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
01256                                     TypePrinting *TypePrinter,
01257                                     SlotTracker *Machine,
01258                                     const Module *Context) {
01259   Out << "!{";
01260   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
01261     const Value *V = Node->getOperand(mi);
01262     if (!V)
01263       Out << "null";
01264     else {
01265       TypePrinter->print(V->getType(), Out);
01266       Out << ' ';
01267       WriteAsOperandInternal(Out, Node->getOperand(mi),
01268                              TypePrinter, Machine, Context);
01269     }
01270     if (mi + 1 != me)
01271       Out << ", ";
01272   }
01273 
01274   Out << "}";
01275 }
01276 
01277 // Full implementation of printing a Value as an operand with support for
01278 // TypePrinting, etc.
01279 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
01280                                    TypePrinting *TypePrinter,
01281                                    SlotTracker *Machine,
01282                                    const Module *Context) {
01283   if (V->hasName()) {
01284     PrintLLVMName(Out, V);
01285     return;
01286   }
01287 
01288   const Constant *CV = dyn_cast<Constant>(V);
01289   if (CV && !isa<GlobalValue>(CV)) {
01290     assert(TypePrinter && "Constants require TypePrinting!");
01291     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
01292     return;
01293   }
01294 
01295   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01296     Out << "asm ";
01297     if (IA->hasSideEffects())
01298       Out << "sideeffect ";
01299     if (IA->isAlignStack())
01300       Out << "alignstack ";
01301     // We don't emit the AD_ATT dialect as it's the assumed default.
01302     if (IA->getDialect() == InlineAsm::AD_Intel)
01303       Out << "inteldialect ";
01304     Out << '"';
01305     PrintEscapedString(IA->getAsmString(), Out);
01306     Out << "\", \"";
01307     PrintEscapedString(IA->getConstraintString(), Out);
01308     Out << '"';
01309     return;
01310   }
01311 
01312   if (const MDNode *N = dyn_cast<MDNode>(V)) {
01313     if (N->isFunctionLocal()) {
01314       // Print metadata inline, not via slot reference number.
01315       WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
01316       return;
01317     }
01318 
01319     if (!Machine) {
01320       if (N->isFunctionLocal())
01321         Machine = new SlotTracker(N->getFunction());
01322       else
01323         Machine = new SlotTracker(Context);
01324     }
01325     int Slot = Machine->getMetadataSlot(N);
01326     if (Slot == -1)
01327       Out << "<badref>";
01328     else
01329       Out << '!' << Slot;
01330     return;
01331   }
01332 
01333   if (const MDString *MDS = dyn_cast<MDString>(V)) {
01334     Out << "!\"";
01335     PrintEscapedString(MDS->getString(), Out);
01336     Out << '"';
01337     return;
01338   }
01339 
01340   char Prefix = '%';
01341   int Slot;
01342   // If we have a SlotTracker, use it.
01343   if (Machine) {
01344     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01345       Slot = Machine->getGlobalSlot(GV);
01346       Prefix = '@';
01347     } else {
01348       Slot = Machine->getLocalSlot(V);
01349 
01350       // If the local value didn't succeed, then we may be referring to a value
01351       // from a different function.  Translate it, as this can happen when using
01352       // address of blocks.
01353       if (Slot == -1)
01354         if ((Machine = createSlotTracker(V))) {
01355           Slot = Machine->getLocalSlot(V);
01356           delete Machine;
01357         }
01358     }
01359   } else if ((Machine = createSlotTracker(V))) {
01360     // Otherwise, create one to get the # and then destroy it.
01361     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01362       Slot = Machine->getGlobalSlot(GV);
01363       Prefix = '@';
01364     } else {
01365       Slot = Machine->getLocalSlot(V);
01366     }
01367     delete Machine;
01368     Machine = nullptr;
01369   } else {
01370     Slot = -1;
01371   }
01372 
01373   if (Slot != -1)
01374     Out << Prefix << Slot;
01375   else
01376     Out << "<badref>";
01377 }
01378 
01379 void AssemblyWriter::init() {
01380   if (!TheModule)
01381     return;
01382   TypePrinter.incorporateTypes(*TheModule);
01383   for (const Function &F : *TheModule)
01384     if (const Comdat *C = F.getComdat())
01385       Comdats.insert(C);
01386   for (const GlobalVariable &GV : TheModule->globals())
01387     if (const Comdat *C = GV.getComdat())
01388       Comdats.insert(C);
01389 }
01390 
01391 
01392 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
01393                                const Module *M,
01394                                AssemblyAnnotationWriter *AAW)
01395   : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
01396   init();
01397 }
01398 
01399 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
01400                                AssemblyAnnotationWriter *AAW)
01401   : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
01402     Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
01403   init();
01404 }
01405 
01406 AssemblyWriter::~AssemblyWriter() { }
01407 
01408 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
01409   if (!Operand) {
01410     Out << "<null operand!>";
01411     return;
01412   }
01413   if (PrintType) {
01414     TypePrinter.print(Operand->getType(), Out);
01415     Out << ' ';
01416   }
01417   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
01418 }
01419 
01420 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
01421                                  SynchronizationScope SynchScope) {
01422   if (Ordering == NotAtomic)
01423     return;
01424 
01425   switch (SynchScope) {
01426   case SingleThread: Out << " singlethread"; break;
01427   case CrossThread: break;
01428   }
01429 
01430   switch (Ordering) {
01431   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
01432   case Unordered: Out << " unordered"; break;
01433   case Monotonic: Out << " monotonic"; break;
01434   case Acquire: Out << " acquire"; break;
01435   case Release: Out << " release"; break;
01436   case AcquireRelease: Out << " acq_rel"; break;
01437   case SequentiallyConsistent: Out << " seq_cst"; break;
01438   }
01439 }
01440 
01441 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
01442                                         AtomicOrdering FailureOrdering,
01443                                         SynchronizationScope SynchScope) {
01444   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
01445 
01446   switch (SynchScope) {
01447   case SingleThread: Out << " singlethread"; break;
01448   case CrossThread: break;
01449   }
01450 
01451   switch (SuccessOrdering) {
01452   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
01453   case Unordered: Out << " unordered"; break;
01454   case Monotonic: Out << " monotonic"; break;
01455   case Acquire: Out << " acquire"; break;
01456   case Release: Out << " release"; break;
01457   case AcquireRelease: Out << " acq_rel"; break;
01458   case SequentiallyConsistent: Out << " seq_cst"; break;
01459   }
01460 
01461   switch (FailureOrdering) {
01462   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
01463   case Unordered: Out << " unordered"; break;
01464   case Monotonic: Out << " monotonic"; break;
01465   case Acquire: Out << " acquire"; break;
01466   case Release: Out << " release"; break;
01467   case AcquireRelease: Out << " acq_rel"; break;
01468   case SequentiallyConsistent: Out << " seq_cst"; break;
01469   }
01470 }
01471 
01472 void AssemblyWriter::writeParamOperand(const Value *Operand,
01473                                        AttributeSet Attrs, unsigned Idx) {
01474   if (!Operand) {
01475     Out << "<null operand!>";
01476     return;
01477   }
01478 
01479   // Print the type
01480   TypePrinter.print(Operand->getType(), Out);
01481   // Print parameter attributes list
01482   if (Attrs.hasAttributes(Idx))
01483     Out << ' ' << Attrs.getAsString(Idx);
01484   Out << ' ';
01485   // Print the operand
01486   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
01487 }
01488 
01489 void AssemblyWriter::printModule(const Module *M) {
01490   Machine.initialize();
01491 
01492   if (shouldPreserveAssemblyUseListOrder())
01493     UseListOrders = predictUseListOrder(M);
01494 
01495   if (!M->getModuleIdentifier().empty() &&
01496       // Don't print the ID if it will start a new line (which would
01497       // require a comment char before it).
01498       M->getModuleIdentifier().find('\n') == std::string::npos)
01499     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
01500 
01501   const std::string &DL = M->getDataLayoutStr();
01502   if (!DL.empty())
01503     Out << "target datalayout = \"" << DL << "\"\n";
01504   if (!M->getTargetTriple().empty())
01505     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
01506 
01507   if (!M->getModuleInlineAsm().empty()) {
01508     // Split the string into lines, to make it easier to read the .ll file.
01509     std::string Asm = M->getModuleInlineAsm();
01510     size_t CurPos = 0;
01511     size_t NewLine = Asm.find_first_of('\n', CurPos);
01512     Out << '\n';
01513     while (NewLine != std::string::npos) {
01514       // We found a newline, print the portion of the asm string from the
01515       // last newline up to this newline.
01516       Out << "module asm \"";
01517       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
01518                          Out);
01519       Out << "\"\n";
01520       CurPos = NewLine+1;
01521       NewLine = Asm.find_first_of('\n', CurPos);
01522     }
01523     std::string rest(Asm.begin()+CurPos, Asm.end());
01524     if (!rest.empty()) {
01525       Out << "module asm \"";
01526       PrintEscapedString(rest, Out);
01527       Out << "\"\n";
01528     }
01529   }
01530 
01531   printTypeIdentities();
01532 
01533   // Output all comdats.
01534   if (!Comdats.empty())
01535     Out << '\n';
01536   for (const Comdat *C : Comdats) {
01537     printComdat(C);
01538     if (C != Comdats.back())
01539       Out << '\n';
01540   }
01541 
01542   // Output all globals.
01543   if (!M->global_empty()) Out << '\n';
01544   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
01545        I != E; ++I) {
01546     printGlobal(I); Out << '\n';
01547   }
01548 
01549   // Output all aliases.
01550   if (!M->alias_empty()) Out << "\n";
01551   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
01552        I != E; ++I)
01553     printAlias(I);
01554 
01555   // Output global use-lists.
01556   printUseLists(nullptr);
01557 
01558   // Output all of the functions.
01559   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
01560     printFunction(I);
01561   assert(UseListOrders.empty() && "All use-lists should have been consumed");
01562 
01563   // Output all attribute groups.
01564   if (!Machine.as_empty()) {
01565     Out << '\n';
01566     writeAllAttributeGroups();
01567   }
01568 
01569   // Output named metadata.
01570   if (!M->named_metadata_empty()) Out << '\n';
01571 
01572   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
01573        E = M->named_metadata_end(); I != E; ++I)
01574     printNamedMDNode(I);
01575 
01576   // Output metadata.
01577   if (!Machine.mdn_empty()) {
01578     Out << '\n';
01579     writeAllMDNodes();
01580   }
01581 }
01582 
01583 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
01584   Out << '!';
01585   StringRef Name = NMD->getName();
01586   if (Name.empty()) {
01587     Out << "<empty name> ";
01588   } else {
01589     if (isalpha(static_cast<unsigned char>(Name[0])) ||
01590         Name[0] == '-' || Name[0] == '$' ||
01591         Name[0] == '.' || Name[0] == '_')
01592       Out << Name[0];
01593     else
01594       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
01595     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
01596       unsigned char C = Name[i];
01597       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
01598           C == '.' || C == '_')
01599         Out << C;
01600       else
01601         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
01602     }
01603   }
01604   Out << " = !{";
01605   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01606     if (i) Out << ", ";
01607     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
01608     if (Slot == -1)
01609       Out << "<badref>";
01610     else
01611       Out << '!' << Slot;
01612   }
01613   Out << "}\n";
01614 }
01615 
01616 
01617 static void PrintLinkage(GlobalValue::LinkageTypes LT,
01618                          formatted_raw_ostream &Out) {
01619   switch (LT) {
01620   case GlobalValue::ExternalLinkage: break;
01621   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
01622   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
01623   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
01624   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
01625   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
01626   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
01627   case GlobalValue::CommonLinkage:        Out << "common ";         break;
01628   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
01629   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
01630   case GlobalValue::AvailableExternallyLinkage:
01631     Out << "available_externally ";
01632     break;
01633   }
01634 }
01635 
01636 
01637 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
01638                             formatted_raw_ostream &Out) {
01639   switch (Vis) {
01640   case GlobalValue::DefaultVisibility: break;
01641   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
01642   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
01643   }
01644 }
01645 
01646 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
01647                                  formatted_raw_ostream &Out) {
01648   switch (SCT) {
01649   case GlobalValue::DefaultStorageClass: break;
01650   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
01651   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
01652   }
01653 }
01654 
01655 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
01656                                   formatted_raw_ostream &Out) {
01657   switch (TLM) {
01658     case GlobalVariable::NotThreadLocal:
01659       break;
01660     case GlobalVariable::GeneralDynamicTLSModel:
01661       Out << "thread_local ";
01662       break;
01663     case GlobalVariable::LocalDynamicTLSModel:
01664       Out << "thread_local(localdynamic) ";
01665       break;
01666     case GlobalVariable::InitialExecTLSModel:
01667       Out << "thread_local(initialexec) ";
01668       break;
01669     case GlobalVariable::LocalExecTLSModel:
01670       Out << "thread_local(localexec) ";
01671       break;
01672   }
01673 }
01674 
01675 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
01676   if (GV->isMaterializable())
01677     Out << "; Materializable\n";
01678 
01679   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
01680   Out << " = ";
01681 
01682   if (!GV->hasInitializer() && GV->hasExternalLinkage())
01683     Out << "external ";
01684 
01685   PrintLinkage(GV->getLinkage(), Out);
01686   PrintVisibility(GV->getVisibility(), Out);
01687   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
01688   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
01689   if (GV->hasUnnamedAddr())
01690     Out << "unnamed_addr ";
01691 
01692   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
01693     Out << "addrspace(" << AddressSpace << ") ";
01694   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
01695   Out << (GV->isConstant() ? "constant " : "global ");
01696   TypePrinter.print(GV->getType()->getElementType(), Out);
01697 
01698   if (GV->hasInitializer()) {
01699     Out << ' ';
01700     writeOperand(GV->getInitializer(), false);
01701   }
01702 
01703   if (GV->hasSection()) {
01704     Out << ", section \"";
01705     PrintEscapedString(GV->getSection(), Out);
01706     Out << '"';
01707   }
01708   if (GV->hasComdat()) {
01709     Out << ", comdat ";
01710     PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix);
01711   }
01712   if (GV->getAlignment())
01713     Out << ", align " << GV->getAlignment();
01714 
01715   printInfoComment(*GV);
01716 }
01717 
01718 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
01719   if (GA->isMaterializable())
01720     Out << "; Materializable\n";
01721 
01722   // Don't crash when dumping partially built GA
01723   if (!GA->hasName())
01724     Out << "<<nameless>> = ";
01725   else {
01726     PrintLLVMName(Out, GA);
01727     Out << " = ";
01728   }
01729   PrintLinkage(GA->getLinkage(), Out);
01730   PrintVisibility(GA->getVisibility(), Out);
01731   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
01732   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
01733   if (GA->hasUnnamedAddr())
01734     Out << "unnamed_addr ";
01735 
01736   Out << "alias ";
01737 
01738   const Constant *Aliasee = GA->getAliasee();
01739 
01740   if (!Aliasee) {
01741     TypePrinter.print(GA->getType(), Out);
01742     Out << " <<NULL ALIASEE>>";
01743   } else {
01744     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
01745   }
01746 
01747   printInfoComment(*GA);
01748   Out << '\n';
01749 }
01750 
01751 void AssemblyWriter::printComdat(const Comdat *C) {
01752   C->print(Out);
01753 }
01754 
01755 void AssemblyWriter::printTypeIdentities() {
01756   if (TypePrinter.NumberedTypes.empty() &&
01757       TypePrinter.NamedTypes.empty())
01758     return;
01759 
01760   Out << '\n';
01761 
01762   // We know all the numbers that each type is used and we know that it is a
01763   // dense assignment.  Convert the map to an index table.
01764   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
01765   for (DenseMap<StructType*, unsigned>::iterator I =
01766        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
01767        I != E; ++I) {
01768     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
01769     NumberedTypes[I->second] = I->first;
01770   }
01771 
01772   // Emit all numbered types.
01773   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
01774     Out << '%' << i << " = type ";
01775 
01776     // Make sure we print out at least one level of the type structure, so
01777     // that we do not get %2 = type %2
01778     TypePrinter.printStructBody(NumberedTypes[i], Out);
01779     Out << '\n';
01780   }
01781 
01782   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
01783     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
01784     Out << " = type ";
01785 
01786     // Make sure we print out at least one level of the type structure, so
01787     // that we do not get %FILE = type %FILE
01788     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
01789     Out << '\n';
01790   }
01791 }
01792 
01793 /// printFunction - Print all aspects of a function.
01794 ///
01795 void AssemblyWriter::printFunction(const Function *F) {
01796   // Print out the return type and name.
01797   Out << '\n';
01798 
01799   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
01800 
01801   if (F->isMaterializable())
01802     Out << "; Materializable\n";
01803 
01804   const AttributeSet &Attrs = F->getAttributes();
01805   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
01806     AttributeSet AS = Attrs.getFnAttributes();
01807     std::string AttrStr;
01808 
01809     unsigned Idx = 0;
01810     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
01811       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
01812         break;
01813 
01814     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
01815          I != E; ++I) {
01816       Attribute Attr = *I;
01817       if (!Attr.isStringAttribute()) {
01818         if (!AttrStr.empty()) AttrStr += ' ';
01819         AttrStr += Attr.getAsString();
01820       }
01821     }
01822 
01823     if (!AttrStr.empty())
01824       Out << "; Function Attrs: " << AttrStr << '\n';
01825   }
01826 
01827   if (F->isDeclaration())
01828     Out << "declare ";
01829   else
01830     Out << "define ";
01831 
01832   PrintLinkage(F->getLinkage(), Out);
01833   PrintVisibility(F->getVisibility(), Out);
01834   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
01835 
01836   // Print the calling convention.
01837   if (F->getCallingConv() != CallingConv::C) {
01838     PrintCallingConv(F->getCallingConv(), Out);
01839     Out << " ";
01840   }
01841 
01842   FunctionType *FT = F->getFunctionType();
01843   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
01844     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
01845   TypePrinter.print(F->getReturnType(), Out);
01846   Out << ' ';
01847   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
01848   Out << '(';
01849   Machine.incorporateFunction(F);
01850 
01851   // Loop over the arguments, printing them...
01852 
01853   unsigned Idx = 1;
01854   if (!F->isDeclaration()) {
01855     // If this isn't a declaration, print the argument names as well.
01856     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01857          I != E; ++I) {
01858       // Insert commas as we go... the first arg doesn't get a comma
01859       if (I != F->arg_begin()) Out << ", ";
01860       printArgument(I, Attrs, Idx);
01861       Idx++;
01862     }
01863   } else {
01864     // Otherwise, print the types from the function type.
01865     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
01866       // Insert commas as we go... the first arg doesn't get a comma
01867       if (i) Out << ", ";
01868 
01869       // Output type...
01870       TypePrinter.print(FT->getParamType(i), Out);
01871 
01872       if (Attrs.hasAttributes(i+1))
01873         Out << ' ' << Attrs.getAsString(i+1);
01874     }
01875   }
01876 
01877   // Finish printing arguments...
01878   if (FT->isVarArg()) {
01879     if (FT->getNumParams()) Out << ", ";
01880     Out << "...";  // Output varargs portion of signature!
01881   }
01882   Out << ')';
01883   if (F->hasUnnamedAddr())
01884     Out << " unnamed_addr";
01885   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
01886     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
01887   if (F->hasSection()) {
01888     Out << " section \"";
01889     PrintEscapedString(F->getSection(), Out);
01890     Out << '"';
01891   }
01892   if (F->hasComdat()) {
01893     Out << " comdat ";
01894     PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix);
01895   }
01896   if (F->getAlignment())
01897     Out << " align " << F->getAlignment();
01898   if (F->hasGC())
01899     Out << " gc \"" << F->getGC() << '"';
01900   if (F->hasPrefixData()) {
01901     Out << " prefix ";
01902     writeOperand(F->getPrefixData(), true);
01903   }
01904   if (F->isDeclaration()) {
01905     Out << '\n';
01906   } else {
01907     Out << " {";
01908     // Output all of the function's basic blocks.
01909     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
01910       printBasicBlock(I);
01911 
01912     // Output the function's use-lists.
01913     printUseLists(F);
01914 
01915     Out << "}\n";
01916   }
01917 
01918   Machine.purgeFunction();
01919 }
01920 
01921 /// printArgument - This member is called for every argument that is passed into
01922 /// the function.  Simply print it out
01923 ///
01924 void AssemblyWriter::printArgument(const Argument *Arg,
01925                                    AttributeSet Attrs, unsigned Idx) {
01926   // Output type...
01927   TypePrinter.print(Arg->getType(), Out);
01928 
01929   // Output parameter attributes list
01930   if (Attrs.hasAttributes(Idx))
01931     Out << ' ' << Attrs.getAsString(Idx);
01932 
01933   // Output name, if available...
01934   if (Arg->hasName()) {
01935     Out << ' ';
01936     PrintLLVMName(Out, Arg);
01937   }
01938 }
01939 
01940 /// printBasicBlock - This member is called for each basic block in a method.
01941 ///
01942 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
01943   if (BB->hasName()) {              // Print out the label if it exists...
01944     Out << "\n";
01945     PrintLLVMName(Out, BB->getName(), LabelPrefix);
01946     Out << ':';
01947   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
01948     Out << "\n; <label>:";
01949     int Slot = Machine.getLocalSlot(BB);
01950     if (Slot != -1)
01951       Out << Slot;
01952     else
01953       Out << "<badref>";
01954   }
01955 
01956   if (!BB->getParent()) {
01957     Out.PadToColumn(50);
01958     Out << "; Error: Block without parent!";
01959   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
01960     // Output predecessors for the block.
01961     Out.PadToColumn(50);
01962     Out << ";";
01963     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
01964 
01965     if (PI == PE) {
01966       Out << " No predecessors!";
01967     } else {
01968       Out << " preds = ";
01969       writeOperand(*PI, false);
01970       for (++PI; PI != PE; ++PI) {
01971         Out << ", ";
01972         writeOperand(*PI, false);
01973       }
01974     }
01975   }
01976 
01977   Out << "\n";
01978 
01979   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
01980 
01981   // Output all of the instructions in the basic block...
01982   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01983     printInstructionLine(*I);
01984   }
01985 
01986   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
01987 }
01988 
01989 /// printInstructionLine - Print an instruction and a newline character.
01990 void AssemblyWriter::printInstructionLine(const Instruction &I) {
01991   printInstruction(I);
01992   Out << '\n';
01993 }
01994 
01995 /// printInfoComment - Print a little comment after the instruction indicating
01996 /// which slot it occupies.
01997 ///
01998 void AssemblyWriter::printInfoComment(const Value &V) {
01999   if (AnnotationWriter)
02000     AnnotationWriter->printInfoComment(V, Out);
02001 }
02002 
02003 // This member is called for each Instruction in a function..
02004 void AssemblyWriter::printInstruction(const Instruction &I) {
02005   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
02006 
02007   // Print out indentation for an instruction.
02008   Out << "  ";
02009 
02010   // Print out name if it exists...
02011   if (I.hasName()) {
02012     PrintLLVMName(Out, &I);
02013     Out << " = ";
02014   } else if (!I.getType()->isVoidTy()) {
02015     // Print out the def slot taken.
02016     int SlotNum = Machine.getLocalSlot(&I);
02017     if (SlotNum == -1)
02018       Out << "<badref> = ";
02019     else
02020       Out << '%' << SlotNum << " = ";
02021   }
02022 
02023   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02024     if (CI->isMustTailCall())
02025       Out << "musttail ";
02026     else if (CI->isTailCall())
02027       Out << "tail ";
02028   }
02029 
02030   // Print out the opcode...
02031   Out << I.getOpcodeName();
02032 
02033   // If this is an atomic load or store, print out the atomic marker.
02034   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
02035       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
02036     Out << " atomic";
02037 
02038   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
02039     Out << " weak";
02040 
02041   // If this is a volatile operation, print out the volatile marker.
02042   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
02043       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
02044       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
02045       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
02046     Out << " volatile";
02047 
02048   // Print out optimization information.
02049   WriteOptimizationInfo(Out, &I);
02050 
02051   // Print out the compare instruction predicates
02052   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
02053     Out << ' ' << getPredicateText(CI->getPredicate());
02054 
02055   // Print out the atomicrmw operation
02056   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
02057     writeAtomicRMWOperation(Out, RMWI->getOperation());
02058 
02059   // Print out the type of the operands...
02060   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
02061 
02062   // Special case conditional branches to swizzle the condition out to the front
02063   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
02064     const BranchInst &BI(cast<BranchInst>(I));
02065     Out << ' ';
02066     writeOperand(BI.getCondition(), true);
02067     Out << ", ";
02068     writeOperand(BI.getSuccessor(0), true);
02069     Out << ", ";
02070     writeOperand(BI.getSuccessor(1), true);
02071 
02072   } else if (isa<SwitchInst>(I)) {
02073     const SwitchInst& SI(cast<SwitchInst>(I));
02074     // Special case switch instruction to get formatting nice and correct.
02075     Out << ' ';
02076     writeOperand(SI.getCondition(), true);
02077     Out << ", ";
02078     writeOperand(SI.getDefaultDest(), true);
02079     Out << " [";
02080     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
02081          i != e; ++i) {
02082       Out << "\n    ";
02083       writeOperand(i.getCaseValue(), true);
02084       Out << ", ";
02085       writeOperand(i.getCaseSuccessor(), true);
02086     }
02087     Out << "\n  ]";
02088   } else if (isa<IndirectBrInst>(I)) {
02089     // Special case indirectbr instruction to get formatting nice and correct.
02090     Out << ' ';
02091     writeOperand(Operand, true);
02092     Out << ", [";
02093 
02094     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
02095       if (i != 1)
02096         Out << ", ";
02097       writeOperand(I.getOperand(i), true);
02098     }
02099     Out << ']';
02100   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
02101     Out << ' ';
02102     TypePrinter.print(I.getType(), Out);
02103     Out << ' ';
02104 
02105     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
02106       if (op) Out << ", ";
02107       Out << "[ ";
02108       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
02109       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
02110     }
02111   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
02112     Out << ' ';
02113     writeOperand(I.getOperand(0), true);
02114     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
02115       Out << ", " << *i;
02116   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
02117     Out << ' ';
02118     writeOperand(I.getOperand(0), true); Out << ", ";
02119     writeOperand(I.getOperand(1), true);
02120     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
02121       Out << ", " << *i;
02122   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
02123     Out << ' ';
02124     TypePrinter.print(I.getType(), Out);
02125     Out << " personality ";
02126     writeOperand(I.getOperand(0), true); Out << '\n';
02127 
02128     if (LPI->isCleanup())
02129       Out << "          cleanup";
02130 
02131     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
02132       if (i != 0 || LPI->isCleanup()) Out << "\n";
02133       if (LPI->isCatch(i))
02134         Out << "          catch ";
02135       else
02136         Out << "          filter ";
02137 
02138       writeOperand(LPI->getClause(i), true);
02139     }
02140   } else if (isa<ReturnInst>(I) && !Operand) {
02141     Out << " void";
02142   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
02143     // Print the calling convention being used.
02144     if (CI->getCallingConv() != CallingConv::C) {
02145       Out << " ";
02146       PrintCallingConv(CI->getCallingConv(), Out);
02147     }
02148 
02149     Operand = CI->getCalledValue();
02150     PointerType *PTy = cast<PointerType>(Operand->getType());
02151     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
02152     Type *RetTy = FTy->getReturnType();
02153     const AttributeSet &PAL = CI->getAttributes();
02154 
02155     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02156       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02157 
02158     // If possible, print out the short form of the call instruction.  We can
02159     // only do this if the first argument is a pointer to a nonvararg function,
02160     // and if the return type is not a pointer to a function.
02161     //
02162     Out << ' ';
02163     if (!FTy->isVarArg() &&
02164         (!RetTy->isPointerTy() ||
02165          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
02166       TypePrinter.print(RetTy, Out);
02167       Out << ' ';
02168       writeOperand(Operand, false);
02169     } else {
02170       writeOperand(Operand, true);
02171     }
02172     Out << '(';
02173     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
02174       if (op > 0)
02175         Out << ", ";
02176       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
02177     }
02178 
02179     // Emit an ellipsis if this is a musttail call in a vararg function.  This
02180     // is only to aid readability, musttail calls forward varargs by default.
02181     if (CI->isMustTailCall() && CI->getParent() &&
02182         CI->getParent()->getParent() &&
02183         CI->getParent()->getParent()->isVarArg())
02184       Out << ", ...";
02185 
02186     Out << ')';
02187     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02188       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02189   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
02190     Operand = II->getCalledValue();
02191     PointerType *PTy = cast<PointerType>(Operand->getType());
02192     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
02193     Type *RetTy = FTy->getReturnType();
02194     const AttributeSet &PAL = II->getAttributes();
02195 
02196     // Print the calling convention being used.
02197     if (II->getCallingConv() != CallingConv::C) {
02198       Out << " ";
02199       PrintCallingConv(II->getCallingConv(), Out);
02200     }
02201 
02202     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
02203       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
02204 
02205     // If possible, print out the short form of the invoke instruction. We can
02206     // only do this if the first argument is a pointer to a nonvararg function,
02207     // and if the return type is not a pointer to a function.
02208     //
02209     Out << ' ';
02210     if (!FTy->isVarArg() &&
02211         (!RetTy->isPointerTy() ||
02212          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
02213       TypePrinter.print(RetTy, Out);
02214       Out << ' ';
02215       writeOperand(Operand, false);
02216     } else {
02217       writeOperand(Operand, true);
02218     }
02219     Out << '(';
02220     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
02221       if (op)
02222         Out << ", ";
02223       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
02224     }
02225 
02226     Out << ')';
02227     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
02228       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
02229 
02230     Out << "\n          to ";
02231     writeOperand(II->getNormalDest(), true);
02232     Out << " unwind ";
02233     writeOperand(II->getUnwindDest(), true);
02234 
02235   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
02236     Out << ' ';
02237     if (AI->isUsedWithInAlloca())
02238       Out << "inalloca ";
02239     TypePrinter.print(AI->getAllocatedType(), Out);
02240     if (!AI->getArraySize() || AI->isArrayAllocation()) {
02241       Out << ", ";
02242       writeOperand(AI->getArraySize(), true);
02243     }
02244     if (AI->getAlignment()) {
02245       Out << ", align " << AI->getAlignment();
02246     }
02247   } else if (isa<CastInst>(I)) {
02248     if (Operand) {
02249       Out << ' ';
02250       writeOperand(Operand, true);   // Work with broken code
02251     }
02252     Out << " to ";
02253     TypePrinter.print(I.getType(), Out);
02254   } else if (isa<VAArgInst>(I)) {
02255     if (Operand) {
02256       Out << ' ';
02257       writeOperand(Operand, true);   // Work with broken code
02258     }
02259     Out << ", ";
02260     TypePrinter.print(I.getType(), Out);
02261   } else if (Operand) {   // Print the normal way.
02262 
02263     // PrintAllTypes - Instructions who have operands of all the same type
02264     // omit the type from all but the first operand.  If the instruction has
02265     // different type operands (for example br), then they are all printed.
02266     bool PrintAllTypes = false;
02267     Type *TheType = Operand->getType();
02268 
02269     // Select, Store and ShuffleVector always print all types.
02270     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
02271         || isa<ReturnInst>(I)) {
02272       PrintAllTypes = true;
02273     } else {
02274       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
02275         Operand = I.getOperand(i);
02276         // note that Operand shouldn't be null, but the test helps make dump()
02277         // more tolerant of malformed IR
02278         if (Operand && Operand->getType() != TheType) {
02279           PrintAllTypes = true;    // We have differing types!  Print them all!
02280           break;
02281         }
02282       }
02283     }
02284 
02285     if (!PrintAllTypes) {
02286       Out << ' ';
02287       TypePrinter.print(TheType, Out);
02288     }
02289 
02290     Out << ' ';
02291     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
02292       if (i) Out << ", ";
02293       writeOperand(I.getOperand(i), PrintAllTypes);
02294     }
02295   }
02296 
02297   // Print atomic ordering/alignment for memory operations
02298   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
02299     if (LI->isAtomic())
02300       writeAtomic(LI->getOrdering(), LI->getSynchScope());
02301     if (LI->getAlignment())
02302       Out << ", align " << LI->getAlignment();
02303   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
02304     if (SI->isAtomic())
02305       writeAtomic(SI->getOrdering(), SI->getSynchScope());
02306     if (SI->getAlignment())
02307       Out << ", align " << SI->getAlignment();
02308   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
02309     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
02310                        CXI->getSynchScope());
02311   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
02312     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
02313   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
02314     writeAtomic(FI->getOrdering(), FI->getSynchScope());
02315   }
02316 
02317   // Print Metadata info.
02318   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
02319   I.getAllMetadata(InstMD);
02320   if (!InstMD.empty()) {
02321     SmallVector<StringRef, 8> MDNames;
02322     I.getType()->getContext().getMDKindNames(MDNames);
02323     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
02324       unsigned Kind = InstMD[i].first;
02325        if (Kind < MDNames.size()) {
02326          Out << ", !" << MDNames[Kind];
02327        } else {
02328          Out << ", !<unknown kind #" << Kind << ">";
02329        }
02330       Out << ' ';
02331       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
02332                              TheModule);
02333     }
02334   }
02335   printInfoComment(I);
02336 }
02337 
02338 static void WriteMDNodeComment(const MDNode *Node,
02339                                formatted_raw_ostream &Out) {
02340   if (Node->getNumOperands() < 1)
02341     return;
02342 
02343   Value *Op = Node->getOperand(0);
02344   if (!Op || !isa<MDString>(Op))
02345     return;
02346 
02347   DIDescriptor Desc(Node);
02348   if (!Desc.Verify())
02349     return;
02350 
02351   unsigned Tag = Desc.getTag();
02352   Out.PadToColumn(50);
02353   if (dwarf::TagString(Tag)) {
02354     Out << "; ";
02355     Desc.print(Out);
02356   } else if (Tag == dwarf::DW_TAG_user_base) {
02357     Out << "; [ DW_TAG_user_base ]";
02358   }
02359 }
02360 
02361 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
02362   Out << '!' << Slot << " = metadata ";
02363   printMDNodeBody(Node);
02364 }
02365 
02366 void AssemblyWriter::writeAllMDNodes() {
02367   SmallVector<const MDNode *, 16> Nodes;
02368   Nodes.resize(Machine.mdn_size());
02369   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
02370        I != E; ++I)
02371     Nodes[I->second] = cast<MDNode>(I->first);
02372 
02373   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
02374     writeMDNode(i, Nodes[i]);
02375   }
02376 }
02377 
02378 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
02379   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
02380   WriteMDNodeComment(Node, Out);
02381   Out << "\n";
02382 }
02383 
02384 void AssemblyWriter::writeAllAttributeGroups() {
02385   std::vector<std::pair<AttributeSet, unsigned> > asVec;
02386   asVec.resize(Machine.as_size());
02387 
02388   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
02389        I != E; ++I)
02390     asVec[I->second] = *I;
02391 
02392   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
02393          I = asVec.begin(), E = asVec.end(); I != E; ++I)
02394     Out << "attributes #" << I->second << " = { "
02395         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
02396 }
02397 
02398 } // namespace llvm
02399 
02400 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
02401   bool IsInFunction = Machine.getFunction();
02402   if (IsInFunction)
02403     Out << "  ";
02404 
02405   Out << "uselistorder";
02406   if (const BasicBlock *BB =
02407           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
02408     Out << "_bb ";
02409     writeOperand(BB->getParent(), false);
02410     Out << ", ";
02411     writeOperand(BB, false);
02412   } else {
02413     Out << " ";
02414     writeOperand(Order.V, true);
02415   }
02416   Out << ", { ";
02417 
02418   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
02419   Out << Order.Shuffle[0];
02420   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
02421     Out << ", " << Order.Shuffle[I];
02422   Out << " }\n";
02423 }
02424 
02425 void AssemblyWriter::printUseLists(const Function *F) {
02426   auto hasMore =
02427       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
02428   if (!hasMore())
02429     // Nothing to do.
02430     return;
02431 
02432   Out << "\n; uselistorder directives\n";
02433   while (hasMore()) {
02434     printUseListOrder(UseListOrders.back());
02435     UseListOrders.pop_back();
02436   }
02437 }
02438 
02439 //===----------------------------------------------------------------------===//
02440 //                       External Interface declarations
02441 //===----------------------------------------------------------------------===//
02442 
02443 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
02444   SlotTracker SlotTable(this);
02445   formatted_raw_ostream OS(ROS);
02446   AssemblyWriter W(OS, SlotTable, this, AAW);
02447   W.printModule(this);
02448 }
02449 
02450 void NamedMDNode::print(raw_ostream &ROS) const {
02451   SlotTracker SlotTable(getParent());
02452   formatted_raw_ostream OS(ROS);
02453   AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
02454   W.printNamedMDNode(this);
02455 }
02456 
02457 void Comdat::print(raw_ostream &ROS) const {
02458   PrintLLVMName(ROS, getName(), ComdatPrefix);
02459   ROS << " = comdat ";
02460 
02461   switch (getSelectionKind()) {
02462   case Comdat::Any:
02463     ROS << "any";
02464     break;
02465   case Comdat::ExactMatch:
02466     ROS << "exactmatch";
02467     break;
02468   case Comdat::Largest:
02469     ROS << "largest";
02470     break;
02471   case Comdat::NoDuplicates:
02472     ROS << "noduplicates";
02473     break;
02474   case Comdat::SameSize:
02475     ROS << "samesize";
02476     break;
02477   }
02478 
02479   ROS << '\n';
02480 }
02481 
02482 void Type::print(raw_ostream &OS) const {
02483   TypePrinting TP;
02484   TP.print(const_cast<Type*>(this), OS);
02485 
02486   // If the type is a named struct type, print the body as well.
02487   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
02488     if (!STy->isLiteral()) {
02489       OS << " = type ";
02490       TP.printStructBody(STy, OS);
02491     }
02492 }
02493 
02494 void Value::print(raw_ostream &ROS) const {
02495   formatted_raw_ostream OS(ROS);
02496   if (const Instruction *I = dyn_cast<Instruction>(this)) {
02497     const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
02498     SlotTracker SlotTable(F);
02499     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
02500     W.printInstruction(*I);
02501   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
02502     SlotTracker SlotTable(BB->getParent());
02503     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
02504     W.printBasicBlock(BB);
02505   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
02506     SlotTracker SlotTable(GV->getParent());
02507     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
02508     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
02509       W.printGlobal(V);
02510     else if (const Function *F = dyn_cast<Function>(GV))
02511       W.printFunction(F);
02512     else
02513       W.printAlias(cast<GlobalAlias>(GV));
02514   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
02515     const Function *F = N->getFunction();
02516     SlotTracker SlotTable(F);
02517     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
02518     W.printMDNodeBody(N);
02519   } else if (const Constant *C = dyn_cast<Constant>(this)) {
02520     TypePrinting TypePrinter;
02521     TypePrinter.print(C->getType(), OS);
02522     OS << ' ';
02523     WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
02524   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
02525              isa<Argument>(this)) {
02526     this->printAsOperand(OS);
02527   } else {
02528     llvm_unreachable("Unknown value to print out!");
02529   }
02530 }
02531 
02532 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
02533   // Fast path: Don't construct and populate a TypePrinting object if we
02534   // won't be needing any types printed.
02535   if (!PrintType &&
02536       ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
02537        hasName() || isa<GlobalValue>(this))) {
02538     WriteAsOperandInternal(O, this, nullptr, nullptr, M);
02539     return;
02540   }
02541 
02542   if (!M)
02543     M = getModuleFromVal(this);
02544 
02545   TypePrinting TypePrinter;
02546   if (M)
02547     TypePrinter.incorporateTypes(*M);
02548   if (PrintType) {
02549     TypePrinter.print(getType(), O);
02550     O << ' ';
02551   }
02552 
02553   WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
02554 }
02555 
02556 // Value::dump - allow easy printing of Values from the debugger.
02557 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
02558 
02559 // Type::dump - allow easy printing of Types from the debugger.
02560 void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
02561 
02562 // Module::dump() - Allow printing of Modules from the debugger.
02563 void Module::dump() const { print(dbgs(), nullptr); }
02564 
02565 // \brief Allow printing of Comdats from the debugger.
02566 void Comdat::dump() const { print(dbgs()); }
02567 
02568 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
02569 void NamedMDNode::dump() const { print(dbgs()); }