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