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