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