LCOV - code coverage report
Current view: top level - lib/IR - AsmWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1992 2138 93.2 %
Date: 2018-10-20 13:21:21 Functions: 153 166 92.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This library implements `print` family of functions in classes like
      11             : // Module, Function, Value, etc. In-memory representation of those classes is
      12             : // converted to IR strings.
      13             : //
      14             : // Note that these routines must be extremely tolerant of various errors in the
      15             : // LLVM code, because it can be used for debugging transformations.
      16             : //
      17             : //===----------------------------------------------------------------------===//
      18             : 
      19             : #include "llvm/ADT/APFloat.h"
      20             : #include "llvm/ADT/APInt.h"
      21             : #include "llvm/ADT/ArrayRef.h"
      22             : #include "llvm/ADT/DenseMap.h"
      23             : #include "llvm/ADT/None.h"
      24             : #include "llvm/ADT/Optional.h"
      25             : #include "llvm/ADT/STLExtras.h"
      26             : #include "llvm/ADT/SetVector.h"
      27             : #include "llvm/ADT/SmallString.h"
      28             : #include "llvm/ADT/SmallVector.h"
      29             : #include "llvm/ADT/StringExtras.h"
      30             : #include "llvm/ADT/StringRef.h"
      31             : #include "llvm/ADT/iterator_range.h"
      32             : #include "llvm/BinaryFormat/Dwarf.h"
      33             : #include "llvm/Config/llvm-config.h"
      34             : #include "llvm/IR/Argument.h"
      35             : #include "llvm/IR/AssemblyAnnotationWriter.h"
      36             : #include "llvm/IR/Attributes.h"
      37             : #include "llvm/IR/BasicBlock.h"
      38             : #include "llvm/IR/CFG.h"
      39             : #include "llvm/IR/CallSite.h"
      40             : #include "llvm/IR/CallingConv.h"
      41             : #include "llvm/IR/Comdat.h"
      42             : #include "llvm/IR/Constant.h"
      43             : #include "llvm/IR/Constants.h"
      44             : #include "llvm/IR/DebugInfoMetadata.h"
      45             : #include "llvm/IR/DerivedTypes.h"
      46             : #include "llvm/IR/Function.h"
      47             : #include "llvm/IR/GlobalAlias.h"
      48             : #include "llvm/IR/GlobalIFunc.h"
      49             : #include "llvm/IR/GlobalIndirectSymbol.h"
      50             : #include "llvm/IR/GlobalObject.h"
      51             : #include "llvm/IR/GlobalValue.h"
      52             : #include "llvm/IR/GlobalVariable.h"
      53             : #include "llvm/IR/IRPrintingPasses.h"
      54             : #include "llvm/IR/InlineAsm.h"
      55             : #include "llvm/IR/InstrTypes.h"
      56             : #include "llvm/IR/Instruction.h"
      57             : #include "llvm/IR/Instructions.h"
      58             : #include "llvm/IR/LLVMContext.h"
      59             : #include "llvm/IR/Metadata.h"
      60             : #include "llvm/IR/Module.h"
      61             : #include "llvm/IR/ModuleSlotTracker.h"
      62             : #include "llvm/IR/ModuleSummaryIndex.h"
      63             : #include "llvm/IR/Operator.h"
      64             : #include "llvm/IR/Statepoint.h"
      65             : #include "llvm/IR/Type.h"
      66             : #include "llvm/IR/TypeFinder.h"
      67             : #include "llvm/IR/Use.h"
      68             : #include "llvm/IR/UseListOrder.h"
      69             : #include "llvm/IR/User.h"
      70             : #include "llvm/IR/Value.h"
      71             : #include "llvm/Support/AtomicOrdering.h"
      72             : #include "llvm/Support/Casting.h"
      73             : #include "llvm/Support/Compiler.h"
      74             : #include "llvm/Support/Debug.h"
      75             : #include "llvm/Support/ErrorHandling.h"
      76             : #include "llvm/Support/Format.h"
      77             : #include "llvm/Support/FormattedStream.h"
      78             : #include "llvm/Support/raw_ostream.h"
      79             : #include <algorithm>
      80             : #include <cassert>
      81             : #include <cctype>
      82             : #include <cstddef>
      83             : #include <cstdint>
      84             : #include <iterator>
      85             : #include <memory>
      86             : #include <string>
      87             : #include <tuple>
      88             : #include <utility>
      89             : #include <vector>
      90             : 
      91             : using namespace llvm;
      92             : 
      93             : // Make virtual table appear in this compilation unit.
      94             : AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
      95             : 
      96             : //===----------------------------------------------------------------------===//
      97             : // Helper Functions
      98             : //===----------------------------------------------------------------------===//
      99             : 
     100             : namespace {
     101             : 
     102         762 : struct OrderMap {
     103             :   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
     104             : 
     105             :   unsigned size() const { return IDs.size(); }
     106       16834 :   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
     107             : 
     108             :   std::pair<unsigned, bool> lookup(const Value *V) const {
     109          32 :     return IDs.lookup(V);
     110             :   }
     111             : 
     112             :   void index(const Value *V) {
     113             :     // Explicitly sequence get-size and insert-value operations to avoid UB.
     114       13502 :     unsigned ID = IDs.size() + 1;
     115       13502 :     IDs[V].first = ID;
     116             :   }
     117             : };
     118             : 
     119             : } // end anonymous namespace
     120             : 
     121       14900 : static void orderValue(const Value *V, OrderMap &OM) {
     122       14900 :   if (OM.lookup(V).first)
     123             :     return;
     124             : 
     125             :   if (const Constant *C = dyn_cast<Constant>(V))
     126        5184 :     if (C->getNumOperands() && !isa<GlobalValue>(C))
     127        2416 :       for (const Value *Op : C->operands())
     128        1264 :         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
     129         936 :           orderValue(Op, OM);
     130             : 
     131             :   // Note: we cannot cache this lookup above, since inserting into the map
     132             :   // changes the map's size, and thus affects the other IDs.
     133       13502 :   OM.index(V);
     134             : }
     135             : 
     136         762 : static OrderMap orderModule(const Module *M) {
     137             :   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
     138             :   // and ValueEnumerator::incorporateFunction().
     139             :   OrderMap OM;
     140             : 
     141        1676 :   for (const GlobalVariable &G : M->globals()) {
     142         914 :     if (G.hasInitializer())
     143             :       if (!isa<GlobalValue>(G.getInitializer()))
     144         690 :         orderValue(G.getInitializer(), OM);
     145         914 :     orderValue(&G, OM);
     146             :   }
     147         906 :   for (const GlobalAlias &A : M->aliases()) {
     148             :     if (!isa<GlobalValue>(A.getAliasee()))
     149          60 :       orderValue(A.getAliasee(), OM);
     150         144 :     orderValue(&A, OM);
     151             :   }
     152         774 :   for (const GlobalIFunc &I : M->ifuncs()) {
     153             :     if (!isa<GlobalValue>(I.getResolver()))
     154           0 :       orderValue(I.getResolver(), OM);
     155          12 :     orderValue(&I, OM);
     156             :   }
     157        2844 :   for (const Function &F : *M) {
     158        4200 :     for (const Use &U : F.operands())
     159          36 :       if (!isa<GlobalValue>(U.get()))
     160          36 :         orderValue(U.get(), OM);
     161             : 
     162        2082 :     orderValue(&F, OM);
     163             : 
     164        2082 :     if (F.isDeclaration())
     165             :       continue;
     166             : 
     167        3058 :     for (const Argument &A : F.args())
     168        1322 :       orderValue(&A, OM);
     169        3728 :     for (const BasicBlock &BB : F) {
     170        1992 :       orderValue(&BB, OM);
     171        6980 :       for (const Instruction &I : BB) {
     172       16656 :         for (const Value *Op : I.operands())
     173        7188 :           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
     174             :               isa<InlineAsm>(*Op))
     175        1724 :             orderValue(Op, OM);
     176        4988 :         orderValue(&I, OM);
     177             :       }
     178             :     }
     179             :   }
     180         762 :   return OM;
     181             : }
     182             : 
     183        1528 : static void predictValueUseListOrderImpl(const Value *V, const Function *F,
     184             :                                          unsigned ID, const OrderMap &OM,
     185             :                                          UseListOrderStack &Stack) {
     186             :   // Predict use-list order for this one.
     187             :   using Entry = std::pair<const Use *, unsigned>;
     188             :   SmallVector<Entry, 64> List;
     189        6602 :   for (const Use &U : V->uses())
     190             :     // Check if this user will be serialized.
     191        5074 :     if (OM.lookup(U.getUser()).first)
     192        9900 :       List.push_back(std::make_pair(&U, List.size()));
     193             : 
     194        1528 :   if (List.size() < 2)
     195             :     // We may have lost some users.
     196             :     return;
     197             : 
     198             :   bool GetsReversed =
     199        2984 :       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
     200             :   if (auto *BA = dyn_cast<BlockAddress>(V))
     201          32 :     ID = OM.lookup(BA->getBasicBlock()).first;
     202             :   llvm::sort(List, [&](const Entry &L, const Entry &R) {
     203             :     const Use *LU = L.first;
     204             :     const Use *RU = R.first;
     205             :     if (LU == RU)
     206             :       return false;
     207             : 
     208             :     auto LID = OM.lookup(LU->getUser()).first;
     209             :     auto RID = OM.lookup(RU->getUser()).first;
     210             : 
     211             :     // If ID is 4, then expect: 7 6 5 1 2 3.
     212             :     if (LID < RID) {
     213             :       if (GetsReversed)
     214             :         if (RID <= ID)
     215             :           return true;
     216             :       return false;
     217             :     }
     218             :     if (RID < LID) {
     219             :       if (GetsReversed)
     220             :         if (LID <= ID)
     221             :           return false;
     222             :       return true;
     223             :     }
     224             : 
     225             :     // LID and RID are equal, so we have different operands of the same user.
     226             :     // Assume operands are added in order for all instructions.
     227             :     if (GetsReversed)
     228             :       if (LID <= ID)
     229             :         return LU->getOperandNo() < RU->getOperandNo();
     230             :     return LU->getOperandNo() > RU->getOperandNo();
     231             :   });
     232             : 
     233        1460 :   if (std::is_sorted(
     234             :           List.begin(), List.end(),
     235           0 :           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
     236             :     // Order is already correct.
     237             :     return;
     238             : 
     239             :   // Store the shuffle.
     240         855 :   Stack.emplace_back(V, F, List.size());
     241             :   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
     242        4034 :   for (size_t I = 0, E = List.size(); I != E; ++I)
     243        6358 :     Stack.back().Shuffle[I] = List[I].second;
     244             : }
     245             : 
     246       16834 : static void predictValueUseListOrder(const Value *V, const Function *F,
     247             :                                      OrderMap &OM, UseListOrderStack &Stack) {
     248       16834 :   auto &IDPair = OM[V];
     249             :   assert(IDPair.first && "Unmapped value");
     250       16834 :   if (IDPair.second)
     251             :     // Already predicted.
     252             :     return;
     253             : 
     254             :   // Do the actual prediction.
     255       13502 :   IDPair.second = true;
     256       18946 :   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
     257        1528 :     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
     258             : 
     259             :   // Recursive descent into constants.
     260             :   if (const Constant *C = dyn_cast<Constant>(V))
     261        5184 :     if (C->getNumOperands()) // Visit GlobalValues.
     262        5242 :       for (const Value *Op : C->operands())
     263        2222 :         if (isa<Constant>(Op)) // Visit GlobalValues.
     264        2190 :           predictValueUseListOrder(Op, F, OM, Stack);
     265             : }
     266             : 
     267         762 : static UseListOrderStack predictUseListOrder(const Module *M) {
     268         762 :   OrderMap OM = orderModule(M);
     269             : 
     270             :   // Use-list orders need to be serialized after all the users have been added
     271             :   // to a value, or else the shuffles will be incomplete.  Store them per
     272             :   // function in a stack.
     273             :   //
     274             :   // Aside from function order, the order of values doesn't matter much here.
     275             :   UseListOrderStack Stack;
     276             : 
     277             :   // We want to visit the functions backward now so we can list function-local
     278             :   // constants in the last Function they're used in.  Module-level constants
     279             :   // have already been visited above.
     280        2844 :   for (const Function &F : make_range(M->rbegin(), M->rend())) {
     281        2082 :     if (F.isDeclaration())
     282             :       continue;
     283        3728 :     for (const BasicBlock &BB : F)
     284        1992 :       predictValueUseListOrder(&BB, &F, OM, Stack);
     285        3058 :     for (const Argument &A : F.args())
     286        1322 :       predictValueUseListOrder(&A, &F, OM, Stack);
     287        3728 :     for (const BasicBlock &BB : F)
     288        6980 :       for (const Instruction &I : BB)
     289       16656 :         for (const Value *Op : I.operands())
     290        6680 :           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
     291        2232 :             predictValueUseListOrder(Op, &F, OM, Stack);
     292        3728 :     for (const BasicBlock &BB : F)
     293        6980 :       for (const Instruction &I : BB)
     294        4988 :         predictValueUseListOrder(&I, &F, OM, Stack);
     295             :   }
     296             : 
     297             :   // Visit globals last.
     298        1676 :   for (const GlobalVariable &G : M->globals())
     299         914 :     predictValueUseListOrder(&G, nullptr, OM, Stack);
     300        2844 :   for (const Function &F : *M)
     301        2082 :     predictValueUseListOrder(&F, nullptr, OM, Stack);
     302         906 :   for (const GlobalAlias &A : M->aliases())
     303         144 :     predictValueUseListOrder(&A, nullptr, OM, Stack);
     304         774 :   for (const GlobalIFunc &I : M->ifuncs())
     305          12 :     predictValueUseListOrder(&I, nullptr, OM, Stack);
     306        1676 :   for (const GlobalVariable &G : M->globals())
     307         914 :     if (G.hasInitializer())
     308         766 :       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
     309         906 :   for (const GlobalAlias &A : M->aliases())
     310         144 :     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
     311         774 :   for (const GlobalIFunc &I : M->ifuncs())
     312          12 :     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
     313        2844 :   for (const Function &F : *M)
     314        4200 :     for (const Use &U : F.operands())
     315          36 :       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
     316             : 
     317         762 :   return Stack;
     318             : }
     319             : 
     320      305035 : static const Module *getModuleFromVal(const Value *V) {
     321             :   if (const Argument *MA = dyn_cast<Argument>(V))
     322        7214 :     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
     323             : 
     324             :   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
     325       12565 :     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
     326             : 
     327             :   if (const Instruction *I = dyn_cast<Instruction>(V)) {
     328      262753 :     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
     329      262677 :     return M ? M->getParent() : nullptr;
     330             :   }
     331             : 
     332             :   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
     333        1206 :     return GV->getParent();
     334             : 
     335             :   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
     336          10 :     for (const User *U : MAV->users())
     337          10 :       if (isa<Instruction>(U))
     338          10 :         if (const Module *M = getModuleFromVal(U))
     339             :           return M;
     340             :     return nullptr;
     341             :   }
     342             : 
     343             :   return nullptr;
     344             : }
     345             : 
     346       13996 : static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
     347       13996 :   switch (cc) {
     348          65 :   default:                         Out << "cc" << cc; break;
     349         414 :   case CallingConv::Fast:          Out << "fastcc"; break;
     350         502 :   case CallingConv::Cold:          Out << "coldcc"; break;
     351           9 :   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
     352           9 :   case CallingConv::AnyReg:        Out << "anyregcc"; break;
     353          23 :   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
     354          15 :   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
     355          68 :   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
     356          46 :   case CallingConv::GHC:           Out << "ghccc"; break;
     357         144 :   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
     358         128 :   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
     359        5842 :   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
     360         157 :   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
     361         123 :   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
     362          33 :   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
     363          34 :   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
     364         610 :   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
     365         753 :   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
     366          15 :   case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
     367          28 :   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
     368          13 :   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
     369          13 :   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
     370          28 :   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
     371         100 :   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
     372          22 :   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
     373          35 :   case CallingConv::Win64:         Out << "win64cc"; break;
     374         334 :   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
     375         227 :   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
     376        2206 :   case CallingConv::Swift:         Out << "swiftcc"; break;
     377          37 :   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
     378          14 :   case CallingConv::HHVM:          Out << "hhvmcc"; break;
     379          16 :   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
     380          25 :   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
     381           6 :   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
     382           8 :   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
     383           6 :   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
     384          12 :   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
     385         134 :   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
     386          16 :   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
     387        1726 :   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
     388             :   }
     389       13996 : }
     390             : 
     391             : enum PrefixType {
     392             :   GlobalPrefix,
     393             :   ComdatPrefix,
     394             :   LabelPrefix,
     395             :   LocalPrefix,
     396             :   NoPrefix
     397             : };
     398             : 
     399     4904626 : void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
     400             :   assert(!Name.empty() && "Cannot get empty name!");
     401             : 
     402             :   // Scan the name to see if it needs quotes first.
     403     4904626 :   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
     404             :   if (!NeedsQuotes) {
     405    56621486 :     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
     406             :       // By making this unsigned, the value passed in to isalnum will always be
     407             :       // in the range 0-255.  This is important when building with MSVC because
     408             :       // its implementation will assert.  This situation can arise when dealing
     409             :       // with UTF-8 multibyte characters.
     410    51846825 :       unsigned char C = Name[i];
     411    51846825 :       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
     412             :           C != '_') {
     413             :         NeedsQuotes = true;
     414             :         break;
     415             :       }
     416             :     }
     417             :   }
     418             : 
     419             :   // If we didn't need any quotes, just write out the name in one blast.
     420     4904626 :   if (!NeedsQuotes) {
     421     4774661 :     OS << Name;
     422     4774661 :     return;
     423             :   }
     424             : 
     425             :   // Okay, we need quotes.  Output the quotes and escape any scary characters as
     426             :   // needed.
     427             :   OS << '"';
     428      129965 :   printEscapedString(Name, OS);
     429             :   OS << '"';
     430             : }
     431             : 
     432             : /// Turn the specified name into an 'LLVM name', which is either prefixed with %
     433             : /// (if the string only contains simple characters) or is surrounded with ""'s
     434             : /// (if it has special chars in it). Print it out.
     435     4620643 : static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
     436     4620643 :   switch (Prefix) {
     437             :   case NoPrefix:
     438             :     break;
     439             :   case GlobalPrefix:
     440             :     OS << '@';
     441             :     break;
     442             :   case ComdatPrefix:
     443             :     OS << '$';
     444             :     break;
     445             :   case LabelPrefix:
     446             :     break;
     447             :   case LocalPrefix:
     448             :     OS << '%';
     449             :     break;
     450             :   }
     451     4620643 :   printLLVMNameWithoutPrefix(OS, Name);
     452     4620643 : }
     453             : 
     454             : /// Turn the specified name into an 'LLVM name', which is either prefixed with %
     455             : /// (if the string only contains simple characters) or is surrounded with ""'s
     456             : /// (if it has special chars in it). Print it out.
     457     3937334 : static void PrintLLVMName(raw_ostream &OS, const Value *V) {
     458     3937334 :   PrintLLVMName(OS, V->getName(),
     459             :                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
     460     3937334 : }
     461             : 
     462             : namespace {
     463             : 
     464             : class TypePrinting {
     465             : public:
     466       61507 :   TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
     467             : 
     468             :   TypePrinting(const TypePrinting &) = delete;
     469             :   TypePrinting &operator=(const TypePrinting &) = delete;
     470             : 
     471             :   /// The named types that are used by the current module.
     472             :   TypeFinder &getNamedTypes();
     473             : 
     474             :   /// The numbered types, number to type mapping.
     475             :   std::vector<StructType *> &getNumberedTypes();
     476             : 
     477             :   bool empty();
     478             : 
     479             :   void print(Type *Ty, raw_ostream &OS);
     480             : 
     481             :   void printStructBody(StructType *Ty, raw_ostream &OS);
     482             : 
     483             : private:
     484             :   void incorporateTypes();
     485             : 
     486             :   /// A module to process lazily when needed. Set to nullptr as soon as used.
     487             :   const Module *DeferredM;
     488             : 
     489             :   TypeFinder NamedTypes;
     490             : 
     491             :   // The numbered types, along with their value.
     492             :   DenseMap<StructType *, unsigned> Type2Number;
     493             : 
     494             :   std::vector<StructType *> NumberedTypes;
     495             : };
     496             : 
     497             : } // end anonymous namespace
     498             : 
     499             : TypeFinder &TypePrinting::getNamedTypes() {
     500        6173 :   incorporateTypes();
     501             :   return NamedTypes;
     502             : }
     503             : 
     504        6173 : std::vector<StructType *> &TypePrinting::getNumberedTypes() {
     505        6173 :   incorporateTypes();
     506             : 
     507             :   // We know all the numbers that each type is used and we know that it is a
     508             :   // dense assignment. Convert the map to an index table, if it's not done
     509             :   // already (judging from the sizes):
     510       12346 :   if (NumberedTypes.size() == Type2Number.size())
     511        5711 :     return NumberedTypes;
     512             : 
     513         462 :   NumberedTypes.resize(Type2Number.size());
     514        1454 :   for (const auto &P : Type2Number) {
     515             :     assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
     516             :     assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
     517        1984 :     NumberedTypes[P.second] = P.first;
     518             :   }
     519         462 :   return NumberedTypes;
     520             : }
     521             : 
     522             : bool TypePrinting::empty() {
     523       17389 :   incorporateTypes();
     524       17389 :   return NamedTypes.empty() && Type2Number.empty();
     525             : }
     526             : 
     527       49852 : void TypePrinting::incorporateTypes() {
     528       49852 :   if (!DeferredM)
     529             :     return;
     530             : 
     531       17397 :   NamedTypes.run(*DeferredM, false);
     532       17397 :   DeferredM = nullptr;
     533             : 
     534             :   // The list of struct types we got back includes all the struct types, split
     535             :   // the unnamed ones out to a numbering and remove the anonymous structs.
     536             :   unsigned NextNumber = 0;
     537             : 
     538             :   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
     539       59458 :   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
     540       42061 :     StructType *STy = *I;
     541             : 
     542             :     // Ignore anonymous types.
     543       42061 :     if (STy->isLiteral())
     544        9733 :       continue;
     545             : 
     546       32328 :     if (STy->getName().empty())
     547        1007 :       Type2Number[STy] = NextNumber++;
     548             :     else
     549       31321 :       *NextToUse++ = STy;
     550             :   }
     551             : 
     552             :   NamedTypes.erase(NextToUse, NamedTypes.end());
     553             : }
     554             : 
     555             : /// Write the specified type to the specified raw_ostream, making use of type
     556             : /// names or up references to shorten the type name where possible.
     557    10607323 : void TypePrinting::print(Type *Ty, raw_ostream &OS) {
     558    10607323 :   switch (Ty->getTypeID()) {
     559      295595 :   case Type::VoidTyID:      OS << "void"; return;
     560       41162 :   case Type::HalfTyID:      OS << "half"; return;
     561      272621 :   case Type::FloatTyID:     OS << "float"; return;
     562      206520 :   case Type::DoubleTyID:    OS << "double"; return;
     563       12182 :   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
     564        3849 :   case Type::FP128TyID:     OS << "fp128"; return;
     565        1013 :   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
     566      235575 :   case Type::LabelTyID:     OS << "label"; return;
     567       18977 :   case Type::MetadataTyID:  OS << "metadata"; return;
     568        2864 :   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
     569        2618 :   case Type::TokenTyID:     OS << "token"; return;
     570             :   case Type::IntegerTyID:
     571             :     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
     572             :     return;
     573             : 
     574             :   case Type::FunctionTyID: {
     575             :     FunctionType *FTy = cast<FunctionType>(Ty);
     576      223990 :     print(FTy->getReturnType(), OS);
     577      111995 :     OS << " (";
     578      289280 :     for (FunctionType::param_iterator I = FTy->param_begin(),
     579      289280 :          E = FTy->param_end(); I != E; ++I) {
     580      354570 :       if (I != FTy->param_begin())
     581       95543 :         OS << ", ";
     582      177285 :       print(*I, OS);
     583             :     }
     584      111995 :     if (FTy->isVarArg()) {
     585       42674 :       if (FTy->getNumParams()) OS << ", ";
     586       42674 :       OS << "...";
     587             :     }
     588             :     OS << ')';
     589             :     return;
     590             :   }
     591             :   case Type::StructTyID: {
     592             :     StructType *STy = cast<StructType>(Ty);
     593             : 
     594      745686 :     if (STy->isLiteral())
     595      102616 :       return printStructBody(STy, OS);
     596             : 
     597      643070 :     if (!STy->getName().empty())
     598      622953 :       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
     599             : 
     600       20117 :     incorporateTypes();
     601       20117 :     const auto I = Type2Number.find(STy);
     602       20117 :     if (I != Type2Number.end())
     603       20107 :       OS << '%' << I->second;
     604             :     else  // Not enumerated, print the hex address.
     605          10 :       OS << "%\"type " << STy << '\"';
     606             :     return;
     607             :   }
     608             :   case Type::PointerTyID: {
     609             :     PointerType *PTy = cast<PointerType>(Ty);
     610     2836859 :     print(PTy->getElementType(), OS);
     611     2836859 :     if (unsigned AddressSpace = PTy->getAddressSpace())
     612       30548 :       OS << " addrspace(" << AddressSpace << ')';
     613             :     OS << '*';
     614             :     return;
     615             :   }
     616             :   case Type::ArrayTyID: {
     617             :     ArrayType *ATy = cast<ArrayType>(Ty);
     618      323771 :     OS << '[' << ATy->getNumElements() << " x ";
     619      323771 :     print(ATy->getElementType(), OS);
     620             :     OS << ']';
     621             :     return;
     622             :   }
     623             :   case Type::VectorTyID: {
     624             :     VectorType *PTy = cast<VectorType>(Ty);
     625      948801 :     OS << "<" << PTy->getNumElements() << " x ";
     626      948801 :     print(PTy->getElementType(), OS);
     627             :     OS << '>';
     628             :     return;
     629             :   }
     630             :   }
     631           0 :   llvm_unreachable("Invalid TypeID");
     632             : }
     633             : 
     634      135012 : void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
     635      135012 :   if (STy->isOpaque()) {
     636        1764 :     OS << "opaque";
     637        1764 :     return;
     638             :   }
     639             : 
     640      133248 :   if (STy->isPacked())
     641             :     OS << '<';
     642             : 
     643      133248 :   if (STy->getNumElements() == 0) {
     644         576 :     OS << "{}";
     645             :   } else {
     646      132672 :     StructType::element_iterator I = STy->element_begin();
     647      132672 :     OS << "{ ";
     648      132672 :     print(*I++, OS);
     649      471173 :     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
     650      338501 :       OS << ", ";
     651      338501 :       print(*I, OS);
     652             :     }
     653             : 
     654      132672 :     OS << " }";
     655             :   }
     656      133248 :   if (STy->isPacked())
     657             :     OS << '>';
     658             : }
     659             : 
     660             : namespace llvm {
     661             : 
     662             : //===----------------------------------------------------------------------===//
     663             : // SlotTracker Class: Enumerate slot numbers for unnamed values
     664             : //===----------------------------------------------------------------------===//
     665             : /// This class provides computation of slot numbers for LLVM Assembly writing.
     666             : ///
     667             : class SlotTracker {
     668             : public:
     669             :   /// ValueMap - A mapping of Values to slot numbers.
     670             :   using ValueMap = DenseMap<const Value *, unsigned>;
     671             : 
     672             : private:
     673             :   /// TheModule - The module for which we are holding slot numbers.
     674             :   const Module* TheModule;
     675             : 
     676             :   /// TheFunction - The function for which we are holding slot numbers.
     677             :   const Function* TheFunction = nullptr;
     678             :   bool FunctionProcessed = false;
     679             :   bool ShouldInitializeAllMetadata;
     680             : 
     681             :   /// The summary index for which we are holding slot numbers.
     682             :   const ModuleSummaryIndex *TheIndex = nullptr;
     683             : 
     684             :   /// mMap - The slot map for the module level data.
     685             :   ValueMap mMap;
     686             :   unsigned mNext = 0;
     687             : 
     688             :   /// fMap - The slot map for the function level data.
     689             :   ValueMap fMap;
     690             :   unsigned fNext = 0;
     691             : 
     692             :   /// mdnMap - Map for MDNodes.
     693             :   DenseMap<const MDNode*, unsigned> mdnMap;
     694             :   unsigned mdnNext = 0;
     695             : 
     696             :   /// asMap - The slot map for attribute sets.
     697             :   DenseMap<AttributeSet, unsigned> asMap;
     698             :   unsigned asNext = 0;
     699             : 
     700             :   /// ModulePathMap - The slot map for Module paths used in the summary index.
     701             :   StringMap<unsigned> ModulePathMap;
     702             :   unsigned ModulePathNext = 0;
     703             : 
     704             :   /// GUIDMap - The slot map for GUIDs used in the summary index.
     705             :   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
     706             :   unsigned GUIDNext = 0;
     707             : 
     708             :   /// TypeIdMap - The slot map for type ids used in the summary index.
     709             :   StringMap<unsigned> TypeIdMap;
     710             :   unsigned TypeIdNext = 0;
     711             : 
     712             : public:
     713             :   /// Construct from a module.
     714             :   ///
     715             :   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
     716             :   /// functions, giving correct numbering for metadata referenced only from
     717             :   /// within a function (even if no functions have been initialized).
     718             :   explicit SlotTracker(const Module *M,
     719             :                        bool ShouldInitializeAllMetadata = false);
     720             : 
     721             :   /// Construct from a function, starting out in incorp state.
     722             :   ///
     723             :   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
     724             :   /// functions, giving correct numbering for metadata referenced only from
     725             :   /// within a function (even if no functions have been initialized).
     726             :   explicit SlotTracker(const Function *F,
     727             :                        bool ShouldInitializeAllMetadata = false);
     728             : 
     729             :   /// Construct from a module summary index.
     730             :   explicit SlotTracker(const ModuleSummaryIndex *Index);
     731             : 
     732             :   SlotTracker(const SlotTracker &) = delete;
     733             :   SlotTracker &operator=(const SlotTracker &) = delete;
     734             : 
     735             :   /// Return the slot number of the specified value in it's type
     736             :   /// plane.  If something is not in the SlotTracker, return -1.
     737             :   int getLocalSlot(const Value *V);
     738             :   int getGlobalSlot(const GlobalValue *V);
     739             :   int getMetadataSlot(const MDNode *N);
     740             :   int getAttributeGroupSlot(AttributeSet AS);
     741             :   int getModulePathSlot(StringRef Path);
     742             :   int getGUIDSlot(GlobalValue::GUID GUID);
     743             :   int getTypeIdSlot(StringRef Id);
     744             : 
     745             :   /// If you'd like to deal with a function instead of just a module, use
     746             :   /// this method to get its data into the SlotTracker.
     747           0 :   void incorporateFunction(const Function *F) {
     748      252441 :     TheFunction = F;
     749      252441 :     FunctionProcessed = false;
     750           0 :   }
     751             : 
     752           0 :   const Function *getFunction() const { return TheFunction; }
     753             : 
     754             :   /// After calling incorporateFunction, use this method to remove the
     755             :   /// most recently incorporated function from the SlotTracker. This
     756             :   /// will reset the state of the machine back to just the module contents.
     757             :   void purgeFunction();
     758             : 
     759             :   /// MDNode map iterators.
     760             :   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
     761             : 
     762       10578 :   mdn_iterator mdn_begin() { return mdnMap.begin(); }
     763             :   mdn_iterator mdn_end() { return mdnMap.end(); }
     764             :   unsigned mdn_size() const { return mdnMap.size(); }
     765             :   bool mdn_empty() const { return mdnMap.empty(); }
     766             : 
     767             :   /// AttributeSet map iterators.
     768             :   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
     769             : 
     770           0 :   as_iterator as_begin()   { return asMap.begin(); }
     771             :   as_iterator as_end()     { return asMap.end(); }
     772             :   unsigned as_size() const { return asMap.size(); }
     773             :   bool as_empty() const    { return asMap.empty(); }
     774             : 
     775             :   /// GUID map iterators.
     776             :   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
     777             : 
     778             :   /// These functions do the actual initialization.
     779             :   inline void initializeIfNeeded();
     780             :   void initializeIndexIfNeeded();
     781             : 
     782             :   // Implementation Details
     783             : private:
     784             :   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
     785             :   void CreateModuleSlot(const GlobalValue *V);
     786             : 
     787             :   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
     788             :   void CreateMetadataSlot(const MDNode *N);
     789             : 
     790             :   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
     791             :   void CreateFunctionSlot(const Value *V);
     792             : 
     793             :   /// Insert the specified AttributeSet into the slot table.
     794             :   void CreateAttributeSetSlot(AttributeSet AS);
     795             : 
     796             :   inline void CreateModulePathSlot(StringRef Path);
     797             :   void CreateGUIDSlot(GlobalValue::GUID GUID);
     798             :   void CreateTypeIdSlot(StringRef Id);
     799             : 
     800             :   /// Add all of the module level global variables (and their initializers)
     801             :   /// and function declarations, but not the contents of those functions.
     802             :   void processModule();
     803             :   void processIndex();
     804             : 
     805             :   /// Add all of the functions arguments, basic blocks, and instructions.
     806             :   void processFunction();
     807             : 
     808             :   /// Add the metadata directly attached to a GlobalObject.
     809             :   void processGlobalObjectMetadata(const GlobalObject &GO);
     810             : 
     811             :   /// Add all of the metadata from a function.
     812             :   void processFunctionMetadata(const Function &F);
     813             : 
     814             :   /// Add all of the metadata from an instruction.
     815             :   void processInstructionMetadata(const Instruction &I);
     816             : };
     817             : 
     818             : } // end namespace llvm
     819             : 
     820       32393 : ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
     821       32393 :                                      const Function *F)
     822       32393 :     : M(M), F(F), Machine(&Machine) {}
     823             : 
     824      143532 : ModuleSlotTracker::ModuleSlotTracker(const Module *M,
     825      143532 :                                      bool ShouldInitializeAllMetadata)
     826             :     : ShouldCreateStorage(M),
     827      143532 :       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
     828             : 
     829             : ModuleSlotTracker::~ModuleSlotTracker() = default;
     830             : 
     831      165878 : SlotTracker *ModuleSlotTracker::getMachine() {
     832      165878 :   if (!ShouldCreateStorage)
     833      122491 :     return Machine;
     834             : 
     835       43387 :   ShouldCreateStorage = false;
     836             :   MachineStorage =
     837       86774 :       llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
     838       43387 :   Machine = MachineStorage.get();
     839       43387 :   return Machine;
     840             : }
     841             : 
     842       43015 : void ModuleSlotTracker::incorporateFunction(const Function &F) {
     843             :   // Using getMachine() may lazily create the slot tracker.
     844       43015 :   if (!getMachine())
     845             :     return;
     846             : 
     847             :   // Nothing to do if this is the right function already.
     848       43015 :   if (this->F == &F)
     849             :     return;
     850       42903 :   if (this->F)
     851          54 :     Machine->purgeFunction();
     852       42903 :   Machine->incorporateFunction(&F);
     853       42903 :   this->F = &F;
     854             : }
     855             : 
     856        4035 : int ModuleSlotTracker::getLocalSlot(const Value *V) {
     857             :   assert(F && "No function incorporated");
     858        4035 :   return Machine->getLocalSlot(V);
     859             : }
     860             : 
     861        1390 : static SlotTracker *createSlotTracker(const Value *V) {
     862             :   if (const Argument *FA = dyn_cast<Argument>(V))
     863          16 :     return new SlotTracker(FA->getParent());
     864             : 
     865             :   if (const Instruction *I = dyn_cast<Instruction>(V))
     866        1166 :     if (I->getParent())
     867        1166 :       return new SlotTracker(I->getParent()->getParent());
     868             : 
     869             :   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
     870         179 :     return new SlotTracker(BB->getParent());
     871             : 
     872             :   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
     873          20 :     return new SlotTracker(GV->getParent());
     874             : 
     875             :   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
     876           0 :     return new SlotTracker(GA->getParent());
     877             : 
     878             :   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
     879           0 :     return new SlotTracker(GIF->getParent());
     880             : 
     881             :   if (const Function *Func = dyn_cast<Function>(V))
     882           9 :     return new SlotTracker(Func);
     883             : 
     884             :   return nullptr;
     885             : }
     886             : 
     887             : #if 0
     888             : #define ST_DEBUG(X) dbgs() << X
     889             : #else
     890             : #define ST_DEBUG(X)
     891             : #endif
     892             : 
     893             : // Module level constructor. Causes the contents of the Module (sans functions)
     894             : // to be added to the slot table.
     895      129015 : SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
     896      129015 :     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
     897             : 
     898             : // Function level constructor. Causes the contents of the Module and the one
     899             : // function provided to be added to the slot table.
     900        1370 : SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
     901        1370 :     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
     902        1370 :       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
     903             : 
     904          69 : SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
     905          69 :     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
     906             : 
     907     2036318 : inline void SlotTracker::initializeIfNeeded() {
     908     2036318 :   if (TheModule) {
     909       27158 :     processModule();
     910       27158 :     TheModule = nullptr; ///< Prevent re-processing next time we're called.
     911             :   }
     912             : 
     913     2036318 :   if (TheFunction && !FunctionProcessed)
     914      164952 :     processFunction();
     915     2036318 : }
     916             : 
     917         874 : void SlotTracker::initializeIndexIfNeeded() {
     918         874 :   if (!TheIndex)
     919             :     return;
     920          69 :   processIndex();
     921          69 :   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
     922             : }
     923             : 
     924             : // Iterate through all the global variables, functions, and global
     925             : // variable initializers and create slots for them.
     926       27158 : void SlotTracker::processModule() {
     927             :   ST_DEBUG("begin processModule!\n");
     928             : 
     929             :   // Add all of the unnamed global variables to the value table.
     930      115303 :   for (const GlobalVariable &Var : TheModule->globals()) {
     931       88145 :     if (!Var.hasName())
     932        5952 :       CreateModuleSlot(&Var);
     933       88145 :     processGlobalObjectMetadata(Var);
     934             :     auto Attrs = Var.getAttributes();
     935       88145 :     if (Attrs.hasAttributes())
     936          33 :       CreateAttributeSetSlot(Attrs);
     937             :   }
     938             : 
     939       28375 :   for (const GlobalAlias &A : TheModule->aliases()) {
     940        1217 :     if (!A.hasName())
     941           4 :       CreateModuleSlot(&A);
     942             :   }
     943             : 
     944       27239 :   for (const GlobalIFunc &I : TheModule->ifuncs()) {
     945          81 :     if (!I.hasName())
     946           0 :       CreateModuleSlot(&I);
     947             :   }
     948             : 
     949             :   // Add metadata used by named metadata.
     950       49035 :   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
     951       57502 :     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
     952       35625 :       CreateMetadataSlot(NMD.getOperand(i));
     953             :   }
     954             : 
     955      397082 :   for (const Function &F : *TheModule) {
     956      369924 :     if (!F.hasName())
     957             :       // Add all the unnamed functions to the table.
     958          39 :       CreateModuleSlot(&F);
     959             : 
     960      369924 :     if (ShouldInitializeAllMetadata)
     961       54563 :       processFunctionMetadata(F);
     962             : 
     963             :     // Add all the function attributes to the table.
     964             :     // FIXME: Add attributes of other objects?
     965      369924 :     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
     966      369924 :     if (FnAttrs.hasAttributes())
     967      243522 :       CreateAttributeSetSlot(FnAttrs);
     968             :   }
     969             : 
     970             :   ST_DEBUG("end processModule!\n");
     971       27158 : }
     972             : 
     973             : // Process the arguments, basic blocks, and instructions  of a function.
     974      164952 : void SlotTracker::processFunction() {
     975             :   ST_DEBUG("begin processFunction!\n");
     976      164952 :   fNext = 0;
     977             : 
     978             :   // Process function metadata if it wasn't hit at the module-level.
     979      164952 :   if (!ShouldInitializeAllMetadata)
     980      162530 :     processFunctionMetadata(*TheFunction);
     981             : 
     982             :   // Add all the function arguments with no names.
     983      421579 :   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
     984      586531 :       AE = TheFunction->arg_end(); AI != AE; ++AI)
     985      256627 :     if (!AI->hasName())
     986       84798 :       CreateFunctionSlot(&*AI);
     987             : 
     988             :   ST_DEBUG("Inserting Instructions:\n");
     989             : 
     990             :   // Add all of the basic blocks and instructions with no names.
     991      476801 :   for (auto &BB : *TheFunction) {
     992      311849 :     if (!BB.hasName())
     993       22824 :       CreateFunctionSlot(&BB);
     994             : 
     995     2657737 :     for (auto &I : BB) {
     996     4691776 :       if (!I.getType()->isVoidTy() && !I.hasName())
     997      752618 :         CreateFunctionSlot(&I);
     998             : 
     999             :       // We allow direct calls to any llvm.foo function here, because the
    1000             :       // target may not be linked into the optimizer.
    1001     2345888 :       if (auto CS = ImmutableCallSite(&I)) {
    1002             :         // Add all the call attributes to the table.
    1003      177460 :         AttributeSet Attrs = CS.getAttributes().getFnAttributes();
    1004      177460 :         if (Attrs.hasAttributes())
    1005       56852 :           CreateAttributeSetSlot(Attrs);
    1006             :       }
    1007             :     }
    1008             :   }
    1009             : 
    1010      164952 :   FunctionProcessed = true;
    1011             : 
    1012             :   ST_DEBUG("end processFunction!\n");
    1013      164952 : }
    1014             : 
    1015             : // Iterate through all the GUID in the index and create slots for them.
    1016          69 : void SlotTracker::processIndex() {
    1017             :   ST_DEBUG("begin processIndex!\n");
    1018             :   assert(TheIndex);
    1019             : 
    1020             :   // The first block of slots are just the module ids, which start at 0 and are
    1021             :   // assigned consecutively. Since the StringMap iteration order isn't
    1022             :   // guaranteed, use a std::map to order by module ID before assigning slots.
    1023             :   std::map<uint64_t, StringRef> ModuleIdToPathMap;
    1024         218 :   for (auto &ModPath : TheIndex->modulePaths())
    1025          80 :     ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
    1026         149 :   for (auto &ModPair : ModuleIdToPathMap)
    1027          80 :     CreateModulePathSlot(ModPair.second);
    1028             : 
    1029             :   // Start numbering the GUIDs after the module ids.
    1030          69 :   GUIDNext = ModulePathNext;
    1031             : 
    1032         387 :   for (auto &GlobalList : *TheIndex)
    1033         318 :     CreateGUIDSlot(GlobalList.first);
    1034             : 
    1035             :   // Start numbering the TypeIds after the GUIDs.
    1036          69 :   TypeIdNext = GUIDNext;
    1037             : 
    1038          69 :   for (auto TidIter = TheIndex->typeIds().begin();
    1039         170 :        TidIter != TheIndex->typeIds().end(); TidIter++)
    1040          16 :     CreateTypeIdSlot(TidIter->second.first);
    1041             : 
    1042             :   ST_DEBUG("end processIndex!\n");
    1043          69 : }
    1044             : 
    1045      305238 : void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
    1046             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    1047      305238 :   GO.getAllMetadata(MDs);
    1048      312747 :   for (auto &MD : MDs)
    1049        7509 :     CreateMetadataSlot(MD.second);
    1050      305238 : }
    1051             : 
    1052      217093 : void SlotTracker::processFunctionMetadata(const Function &F) {
    1053      217093 :   processGlobalObjectMetadata(F);
    1054      583360 :   for (auto &BB : F) {
    1055     2839408 :     for (auto &I : BB)
    1056     2473141 :       processInstructionMetadata(I);
    1057             :   }
    1058      217093 : }
    1059             : 
    1060     2473141 : void SlotTracker::processInstructionMetadata(const Instruction &I) {
    1061             :   // Process metadata used directly by intrinsics.
    1062             :   if (const CallInst *CI = dyn_cast<CallInst>(&I))
    1063             :     if (Function *F = CI->getCalledFunction())
    1064      174415 :       if (F->isIntrinsic())
    1065      354829 :         for (auto &Op : I.operands())
    1066             :           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
    1067       21542 :             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
    1068       14321 :               CreateMetadataSlot(N);
    1069             : 
    1070             :   // Process metadata attached to this instruction.
    1071             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    1072             :   I.getAllMetadata(MDs);
    1073     2646806 :   for (auto &MD : MDs)
    1074      173665 :     CreateMetadataSlot(MD.second);
    1075     2473141 : }
    1076             : 
    1077             : /// Clean up after incorporating a function. This is the only way to get out of
    1078             : /// the function incorporation state that affects get*Slot/Create*Slot. Function
    1079             : /// incorporation state is indicated by TheFunction != 0.
    1080      209592 : void SlotTracker::purgeFunction() {
    1081             :   ST_DEBUG("begin purgeFunction!\n");
    1082      209592 :   fMap.clear(); // Simply discard the function level map
    1083      209592 :   TheFunction = nullptr;
    1084      209592 :   FunctionProcessed = false;
    1085             :   ST_DEBUG("end purgeFunction!\n");
    1086      209592 : }
    1087             : 
    1088             : /// getGlobalSlot - Get the slot number of a global value.
    1089       29938 : int SlotTracker::getGlobalSlot(const GlobalValue *V) {
    1090             :   // Check for uninitialized state and do lazy initialization.
    1091       29938 :   initializeIfNeeded();
    1092             : 
    1093             :   // Find the value in the module map
    1094       29938 :   ValueMap::iterator MI = mMap.find(V);
    1095       29938 :   return MI == mMap.end() ? -1 : (int)MI->second;
    1096             : }
    1097             : 
    1098             : /// getMetadataSlot - Get the slot number of a MDNode.
    1099      304148 : int SlotTracker::getMetadataSlot(const MDNode *N) {
    1100             :   // Check for uninitialized state and do lazy initialization.
    1101      304148 :   initializeIfNeeded();
    1102             : 
    1103             :   // Find the MDNode in the module map
    1104      304148 :   mdn_iterator MI = mdnMap.find(N);
    1105      304148 :   return MI == mdnMap.end() ? -1 : (int)MI->second;
    1106             : }
    1107             : 
    1108             : /// getLocalSlot - Get the slot number for a value that is local to a function.
    1109     1481671 : int SlotTracker::getLocalSlot(const Value *V) {
    1110             :   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
    1111             : 
    1112             :   // Check for uninitialized state and do lazy initialization.
    1113     1481671 :   initializeIfNeeded();
    1114             : 
    1115     1481671 :   ValueMap::iterator FI = fMap.find(V);
    1116     1481671 :   return FI == fMap.end() ? -1 : (int)FI->second;
    1117             : }
    1118             : 
    1119      203172 : int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
    1120             :   // Check for uninitialized state and do lazy initialization.
    1121      203172 :   initializeIfNeeded();
    1122             : 
    1123             :   // Find the AttributeSet in the module map.
    1124      203172 :   as_iterator AI = asMap.find(AS);
    1125      203172 :   return AI == asMap.end() ? -1 : (int)AI->second;
    1126             : }
    1127             : 
    1128         304 : int SlotTracker::getModulePathSlot(StringRef Path) {
    1129             :   // Check for uninitialized state and do lazy initialization.
    1130         304 :   initializeIndexIfNeeded();
    1131             : 
    1132             :   // Find the Module path in the map
    1133         304 :   auto I = ModulePathMap.find(Path);
    1134         608 :   return I == ModulePathMap.end() ? -1 : (int)I->second;
    1135             : }
    1136             : 
    1137         462 : int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
    1138             :   // Check for uninitialized state and do lazy initialization.
    1139         462 :   initializeIndexIfNeeded();
    1140             : 
    1141             :   // Find the GUID in the map
    1142         462 :   guid_iterator I = GUIDMap.find(GUID);
    1143         462 :   return I == GUIDMap.end() ? -1 : (int)I->second;
    1144             : }
    1145             : 
    1146          39 : int SlotTracker::getTypeIdSlot(StringRef Id) {
    1147             :   // Check for uninitialized state and do lazy initialization.
    1148          39 :   initializeIndexIfNeeded();
    1149             : 
    1150             :   // Find the TypeId string in the map
    1151          39 :   auto I = TypeIdMap.find(Id);
    1152          78 :   return I == TypeIdMap.end() ? -1 : (int)I->second;
    1153             : }
    1154             : 
    1155             : /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
    1156        5995 : void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
    1157             :   assert(V && "Can't insert a null Value into SlotTracker!");
    1158             :   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
    1159             :   assert(!V->hasName() && "Doesn't need a slot!");
    1160             : 
    1161        5995 :   unsigned DestSlot = mNext++;
    1162        5995 :   mMap[V] = DestSlot;
    1163             : 
    1164             :   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
    1165             :            DestSlot << " [");
    1166             :   // G = Global, F = Function, A = Alias, I = IFunc, o = other
    1167             :   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
    1168             :             (isa<Function>(V) ? 'F' :
    1169             :              (isa<GlobalAlias>(V) ? 'A' :
    1170             :               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
    1171        5995 : }
    1172             : 
    1173             : /// CreateSlot - Create a new slot for the specified value if it has no name.
    1174      860240 : void SlotTracker::CreateFunctionSlot(const Value *V) {
    1175             :   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
    1176             : 
    1177      860240 :   unsigned DestSlot = fNext++;
    1178      860240 :   fMap[V] = DestSlot;
    1179             : 
    1180             :   // G = Global, F = Function, o = other
    1181             :   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
    1182             :            DestSlot << " [o]\n");
    1183      860240 : }
    1184             : 
    1185             : /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
    1186      393213 : void SlotTracker::CreateMetadataSlot(const MDNode *N) {
    1187             :   assert(N && "Can't insert a null Value into SlotTracker!");
    1188             : 
    1189             :   // Don't make slots for DIExpressions. We just print them inline everywhere.
    1190      393213 :   if (isa<DIExpression>(N))
    1191             :     return;
    1192             : 
    1193      385430 :   unsigned DestSlot = mdnNext;
    1194      385430 :   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
    1195             :     return;
    1196      136069 :   ++mdnNext;
    1197             : 
    1198             :   // Recursively add any MDNodes referenced by operands.
    1199      551164 :   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
    1200             :     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
    1201      162093 :       CreateMetadataSlot(Op);
    1202             : }
    1203             : 
    1204      300407 : void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
    1205             :   assert(AS.hasAttributes() && "Doesn't need a slot!");
    1206             : 
    1207      300407 :   as_iterator I = asMap.find(AS);
    1208      300407 :   if (I != asMap.end())
    1209      259112 :     return;
    1210             : 
    1211       41295 :   unsigned DestSlot = asNext++;
    1212       41295 :   asMap[AS] = DestSlot;
    1213             : }
    1214             : 
    1215             : /// Create a new slot for the specified Module
    1216          80 : void SlotTracker::CreateModulePathSlot(StringRef Path) {
    1217          80 :   ModulePathMap[Path] = ModulePathNext++;
    1218          80 : }
    1219             : 
    1220             : /// Create a new slot for the specified GUID
    1221         318 : void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
    1222         318 :   GUIDMap[GUID] = GUIDNext++;
    1223         318 : }
    1224             : 
    1225             : /// Create a new slot for the specified Id
    1226          16 : void SlotTracker::CreateTypeIdSlot(StringRef Id) {
    1227          16 :   TypeIdMap[Id] = TypeIdNext++;
    1228          16 : }
    1229             : 
    1230             : //===----------------------------------------------------------------------===//
    1231             : // AsmWriter Implementation
    1232             : //===----------------------------------------------------------------------===//
    1233             : 
    1234             : static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
    1235             :                                    TypePrinting *TypePrinter,
    1236             :                                    SlotTracker *Machine,
    1237             :                                    const Module *Context);
    1238             : 
    1239             : static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
    1240             :                                    TypePrinting *TypePrinter,
    1241             :                                    SlotTracker *Machine, const Module *Context,
    1242             :                                    bool FromValue = false);
    1243             : 
    1244     2423834 : static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
    1245       87482 :   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
    1246             :     // 'Fast' is an abbreviation for all fast-math-flags.
    1247             :     if (FPO->isFast())
    1248        3194 :       Out << " fast";
    1249             :     else {
    1250       84288 :       if (FPO->hasAllowReassoc())
    1251         320 :         Out << " reassoc";
    1252       84288 :       if (FPO->hasNoNaNs())
    1253         295 :         Out << " nnan";
    1254       84288 :       if (FPO->hasNoInfs())
    1255         109 :         Out << " ninf";
    1256       84288 :       if (FPO->hasNoSignedZeros())
    1257         167 :         Out << " nsz";
    1258       84288 :       if (FPO->hasAllowReciprocal())
    1259          82 :         Out << " arcp";
    1260       84288 :       if (FPO->hasAllowContract())
    1261          50 :         Out << " contract";
    1262       84288 :       if (FPO->hasApproxFunc())
    1263          52 :         Out << " afn";
    1264             :     }
    1265             :   }
    1266             : 
    1267      101348 :   if (const OverflowingBinaryOperator *OBO =
    1268             :         dyn_cast<OverflowingBinaryOperator>(U)) {
    1269      101348 :     if (OBO->hasNoUnsignedWrap())
    1270        8020 :       Out << " nuw";
    1271      101348 :     if (OBO->hasNoSignedWrap())
    1272       66286 :       Out << " nsw";
    1273       12756 :   } else if (const PossiblyExactOperator *Div =
    1274             :                dyn_cast<PossiblyExactOperator>(U)) {
    1275       12756 :     if (Div->isExact())
    1276         855 :       Out << " exact";
    1277             :   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
    1278      195492 :     if (GEP->isInBounds())
    1279      176420 :       Out << " inbounds";
    1280             :   }
    1281     2423834 : }
    1282             : 
    1283     1309697 : static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
    1284             :                                   TypePrinting &TypePrinter,
    1285             :                                   SlotTracker *Machine,
    1286             :                                   const Module *Context) {
    1287             :   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
    1288     1014722 :     if (CI->getType()->isIntegerTy(1)) {
    1289       40244 :       Out << (CI->getZExtValue() ? "true" : "false");
    1290       24548 :       return;
    1291             :     }
    1292             :     Out << CI->getValue();
    1293      990174 :     return;
    1294             :   }
    1295             : 
    1296             :   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
    1297             :     const APFloat &APF = CFP->getValueAPF();
    1298       18779 :     if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
    1299        8203 :         &APF.getSemantics() == &APFloat::IEEEdouble()) {
    1300             :       // We would like to output the FP constant value in exponential notation,
    1301             :       // but we cannot do this if doing so will lose precision.  Check here to
    1302             :       // make sure that we only output it in exponential format if we can parse
    1303             :       // the value back and get the same value.
    1304             :       //
    1305             :       bool ignored;
    1306       17620 :       bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
    1307             :       bool isInf = APF.isInfinity();
    1308             :       bool isNaN = APF.isNaN();
    1309       17620 :       if (!isInf && !isNaN) {
    1310       17075 :         double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
    1311             :         SmallString<128> StrVal;
    1312       17075 :         APF.toString(StrVal, 6, 0, false);
    1313             :         // Check to make sure that the stringized number is not some string like
    1314             :         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
    1315             :         // that the string matches the "[-+]?[0-9]" regex.
    1316             :         //
    1317             :         assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
    1318             :                 ((StrVal[0] == '-' || StrVal[0] == '+') &&
    1319             :                  (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
    1320             :                "[-+]?[0-9] regex does not match!");
    1321             :         // Reparse stringized version!
    1322       34150 :         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
    1323             :           Out << StrVal;
    1324             :           return;
    1325             :         }
    1326             :       }
    1327             :       // Otherwise we could not reparse it to exactly the same value, so we must
    1328             :       // output the string in hexadecimal format!  Note that loading and storing
    1329             :       // floating point types changes the bits of NaNs on some hosts, notably
    1330             :       // x86, so we must not use these types.
    1331             :       static_assert(sizeof(double) == sizeof(uint64_t),
    1332             :                     "assuming that double is 64 bits!");
    1333             :       APFloat apf = APF;
    1334             :       // Floats are represented in ASCII IR as double, convert.
    1335        1054 :       if (!isDouble)
    1336         650 :         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
    1337             :                           &ignored);
    1338        2108 :       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
    1339             :       return;
    1340             :     }
    1341             : 
    1342             :     // Either half, or some form of long double.
    1343             :     // These appear as a magic letter identifying the type, then a
    1344             :     // fixed number of hex digits.
    1345        1159 :     Out << "0x";
    1346        1159 :     APInt API = APF.bitcastToAPInt();
    1347        1159 :     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
    1348             :       Out << 'K';
    1349         634 :       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
    1350         317 :                                   /*Upper=*/true);
    1351         634 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1352         317 :                                   /*Upper=*/true);
    1353         317 :       return;
    1354         842 :     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
    1355             :       Out << 'L';
    1356         432 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1357         216 :                                   /*Upper=*/true);
    1358         648 :       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
    1359         216 :                                   /*Upper=*/true);
    1360         626 :     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
    1361             :       Out << 'M';
    1362          54 :       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
    1363          27 :                                   /*Upper=*/true);
    1364          81 :       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
    1365          27 :                                   /*Upper=*/true);
    1366         599 :     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
    1367             :       Out << 'H';
    1368         599 :       Out << format_hex_no_prefix(API.getZExtValue(), 4,
    1369         599 :                                   /*Upper=*/true);
    1370             :     } else
    1371           0 :       llvm_unreachable("Unsupported floating point type");
    1372         842 :     return;
    1373             :   }
    1374             : 
    1375      276196 :   if (isa<ConstantAggregateZero>(CV)) {
    1376       15432 :     Out << "zeroinitializer";
    1377       15432 :     return;
    1378             :   }
    1379             : 
    1380             :   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
    1381         324 :     Out << "blockaddress(";
    1382         324 :     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
    1383             :                            Context);
    1384         324 :     Out << ", ";
    1385         324 :     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
    1386             :                            Context);
    1387         324 :     Out << ")";
    1388         324 :     return;
    1389             :   }
    1390             : 
    1391             :   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
    1392        8151 :     Type *ETy = CA->getType()->getElementType();
    1393             :     Out << '[';
    1394        8151 :     TypePrinter.print(ETy, Out);
    1395             :     Out << ' ';
    1396        8151 :     WriteAsOperandInternal(Out, CA->getOperand(0),
    1397             :                            &TypePrinter, Machine,
    1398             :                            Context);
    1399       25851 :     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
    1400       17700 :       Out << ", ";
    1401       17700 :       TypePrinter.print(ETy, Out);
    1402             :       Out << ' ';
    1403       17700 :       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
    1404             :                              Context);
    1405             :     }
    1406             :     Out << ']';
    1407        8151 :     return;
    1408             :   }
    1409             : 
    1410             :   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
    1411             :     // As a special case, print the array as a string if it is an array of
    1412             :     // i8 with ConstantInt values.
    1413       24453 :     if (CA->isString()) {
    1414       16813 :       Out << "c\"";
    1415       16813 :       printEscapedString(CA->getAsString(), Out);
    1416             :       Out << '"';
    1417       16813 :       return;
    1418             :     }
    1419             : 
    1420        7640 :     Type *ETy = CA->getType()->getElementType();
    1421             :     Out << '[';
    1422        7640 :     TypePrinter.print(ETy, Out);
    1423             :     Out << ' ';
    1424        7640 :     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
    1425             :                            &TypePrinter, Machine,
    1426             :                            Context);
    1427       19097 :     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
    1428       11457 :       Out << ", ";
    1429       11457 :       TypePrinter.print(ETy, Out);
    1430             :       Out << ' ';
    1431       11457 :       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
    1432             :                              Machine, Context);
    1433             :     }
    1434             :     Out << ']';
    1435        7640 :     return;
    1436             :   }
    1437             : 
    1438             :   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
    1439       27372 :     if (CS->getType()->isPacked())
    1440             :       Out << '<';
    1441             :     Out << '{';
    1442             :     unsigned N = CS->getNumOperands();
    1443       27372 :     if (N) {
    1444             :       Out << ' ';
    1445       27372 :       TypePrinter.print(CS->getOperand(0)->getType(), Out);
    1446             :       Out << ' ';
    1447             : 
    1448       27372 :       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
    1449             :                              Context);
    1450             : 
    1451      112359 :       for (unsigned i = 1; i < N; i++) {
    1452       84987 :         Out << ", ";
    1453       84987 :         TypePrinter.print(CS->getOperand(i)->getType(), Out);
    1454             :         Out << ' ';
    1455             : 
    1456       84987 :         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
    1457             :                                Context);
    1458             :       }
    1459             :       Out << ' ';
    1460             :     }
    1461             : 
    1462             :     Out << '}';
    1463       27372 :     if (CS->getType()->isPacked())
    1464             :       Out << '>';
    1465       27372 :     return;
    1466             :   }
    1467             : 
    1468      200464 :   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
    1469       22595 :     Type *ETy = CV->getType()->getVectorElementType();
    1470             :     Out << '<';
    1471       22595 :     TypePrinter.print(ETy, Out);
    1472             :     Out << ' ';
    1473       22595 :     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
    1474             :                            Machine, Context);
    1475      202490 :     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
    1476      179895 :       Out << ", ";
    1477      179895 :       TypePrinter.print(ETy, Out);
    1478             :       Out << ' ';
    1479      179895 :       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
    1480             :                              Machine, Context);
    1481             :     }
    1482             :     Out << '>';
    1483       22595 :     return;
    1484             :   }
    1485             : 
    1486      177869 :   if (isa<ConstantPointerNull>(CV)) {
    1487       23378 :     Out << "null";
    1488       23378 :     return;
    1489             :   }
    1490             : 
    1491      154491 :   if (isa<ConstantTokenNone>(CV)) {
    1492         620 :     Out << "none";
    1493         620 :     return;
    1494             :   }
    1495             : 
    1496      153871 :   if (isa<UndefValue>(CV)) {
    1497       45034 :     Out << "undef";
    1498       45034 :     return;
    1499             :   }
    1500             : 
    1501             :   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
    1502      108837 :     Out << CE->getOpcodeName();
    1503      108837 :     WriteOptimizationInfo(Out, CE);
    1504      108837 :     if (CE->isCompare())
    1505             :       Out << ' ' << CmpInst::getPredicateName(
    1506         236 :                         static_cast<CmpInst::Predicate>(CE->getPredicate()));
    1507      108837 :     Out << " (";
    1508             : 
    1509             :     Optional<unsigned> InRangeOp;
    1510             :     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
    1511       49625 :       TypePrinter.print(GEP->getSourceElementType(), Out);
    1512       49625 :       Out << ", ";
    1513             :       InRangeOp = GEP->getInRangeIndex();
    1514       49625 :       if (InRangeOp)
    1515        1371 :         ++*InRangeOp;
    1516             :     }
    1517             : 
    1518      320514 :     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
    1519      211677 :       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
    1520        1371 :         Out << "inrange ";
    1521      211677 :       TypePrinter.print((*OI)->getType(), Out);
    1522             :       Out << ' ';
    1523      211677 :       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
    1524      211677 :       if (OI+1 != CE->op_end())
    1525      102840 :         Out << ", ";
    1526             :     }
    1527             : 
    1528      108837 :     if (CE->hasIndices()) {
    1529           3 :       ArrayRef<unsigned> Indices = CE->getIndices();
    1530           6 :       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
    1531           3 :         Out << ", " << Indices[i];
    1532             :     }
    1533             : 
    1534      108837 :     if (CE->isCast()) {
    1535       55845 :       Out << " to ";
    1536       55845 :       TypePrinter.print(CE->getType(), Out);
    1537             :     }
    1538             : 
    1539             :     Out << ')';
    1540             :     return;
    1541             :   }
    1542             : 
    1543           0 :   Out << "<placeholder or erroneous Constant>";
    1544             : }
    1545             : 
    1546       65034 : static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
    1547             :                          TypePrinting *TypePrinter, SlotTracker *Machine,
    1548             :                          const Module *Context) {
    1549       65034 :   Out << "!{";
    1550      236839 :   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
    1551      171805 :     const Metadata *MD = Node->getOperand(mi);
    1552      171805 :     if (!MD)
    1553        1100 :       Out << "null";
    1554             :     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
    1555       77491 :       Value *V = MDV->getValue();
    1556       77491 :       TypePrinter->print(V->getType(), Out);
    1557             :       Out << ' ';
    1558       77491 :       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
    1559             :     } else {
    1560       93214 :       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
    1561             :     }
    1562      171805 :     if (mi + 1 != me)
    1563      108844 :       Out << ", ";
    1564             :   }
    1565             : 
    1566       65034 :   Out << "}";
    1567       65034 : }
    1568             : 
    1569             : namespace {
    1570             : 
    1571             : struct FieldSeparator {
    1572             :   bool Skip = true;
    1573             :   const char *Sep;
    1574             : 
    1575       34904 :   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
    1576             : };
    1577             : 
    1578           0 : raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
    1579          20 :   if (FS.Skip) {
    1580       37850 :     FS.Skip = false;
    1581           0 :     return OS;
    1582             :   }
    1583      133765 :   return OS << FS.Sep;
    1584             : }
    1585             : 
    1586             : struct MDFieldPrinter {
    1587             :   raw_ostream &Out;
    1588             :   FieldSeparator FS;
    1589             :   TypePrinting *TypePrinter = nullptr;
    1590             :   SlotTracker *Machine = nullptr;
    1591             :   const Module *Context = nullptr;
    1592             : 
    1593           0 :   explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
    1594             :   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
    1595             :                  SlotTracker *Machine, const Module *Context)
    1596       12527 :       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
    1597             :   }
    1598             : 
    1599             :   void printTag(const DINode *N);
    1600             :   void printMacinfoType(const DIMacroNode *N);
    1601             :   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
    1602             :   void printString(StringRef Name, StringRef Value,
    1603             :                    bool ShouldSkipEmpty = true);
    1604             :   void printMetadata(StringRef Name, const Metadata *MD,
    1605             :                      bool ShouldSkipNull = true);
    1606             :   template <class IntTy>
    1607             :   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
    1608             :   void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
    1609             :   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
    1610             :   template <class IntTy, class Stringifier>
    1611             :   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
    1612             :                       bool ShouldSkipZero = true);
    1613             :   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
    1614             :   void printNameTableKind(StringRef Name,
    1615             :                           DICompileUnit::DebugNameTableKind NTK);
    1616             : };
    1617             : 
    1618             : } // end anonymous namespace
    1619             : 
    1620        5412 : void MDFieldPrinter::printTag(const DINode *N) {
    1621       10824 :   Out << FS << "tag: ";
    1622       10824 :   auto Tag = dwarf::TagString(N->getTag());
    1623        5412 :   if (!Tag.empty())
    1624        5407 :     Out << Tag;
    1625             :   else
    1626           5 :     Out << N->getTag();
    1627        5412 : }
    1628             : 
    1629        1427 : void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
    1630        2854 :   Out << FS << "type: ";
    1631        2854 :   auto Type = dwarf::MacinfoString(N->getMacinfoType());
    1632        1427 :   if (!Type.empty())
    1633        1427 :     Out << Type;
    1634             :   else
    1635           0 :     Out << N->getMacinfoType();
    1636        1427 : }
    1637             : 
    1638          74 : void MDFieldPrinter::printChecksum(
    1639             :     const DIFile::ChecksumInfo<StringRef> &Checksum) {
    1640         148 :   Out << FS << "checksumkind: " << Checksum.getKindAsString();
    1641          74 :   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
    1642          74 : }
    1643             : 
    1644       35814 : void MDFieldPrinter::printString(StringRef Name, StringRef Value,
    1645             :                                  bool ShouldSkipEmpty) {
    1646       35814 :   if (ShouldSkipEmpty && Value.empty())
    1647             :     return;
    1648             : 
    1649       48982 :   Out << FS << Name << ": \"";
    1650       24491 :   printEscapedString(Value, Out);
    1651       24491 :   Out << "\"";
    1652             : }
    1653             : 
    1654       67823 : static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
    1655             :                                    TypePrinting *TypePrinter,
    1656             :                                    SlotTracker *Machine,
    1657             :                                    const Module *Context) {
    1658       67823 :   if (!MD) {
    1659         569 :     Out << "null";
    1660         569 :     return;
    1661             :   }
    1662       67254 :   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
    1663             : }
    1664             : 
    1665      121214 : void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
    1666             :                                    bool ShouldSkipNull) {
    1667      121214 :   if (ShouldSkipNull && !MD)
    1668             :     return;
    1669             : 
    1670      135616 :   Out << FS << Name << ": ";
    1671       67808 :   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
    1672             : }
    1673             : 
    1674             : template <class IntTy>
    1675       83932 : void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
    1676       83932 :   if (ShouldSkipZero && !Int)
    1677             :     return;
    1678             : 
    1679       85246 :   Out << FS << Name << ": " << Int;
    1680             : }
    1681        4239 : 
    1682        4239 : void MDFieldPrinter::printBool(StringRef Name, bool Value,
    1683             :                                Optional<bool> Default) {
    1684             :   if (Default && Value == *Default)
    1685          20 :     return;
    1686             :   Out << FS << Name << ": " << (Value ? "true" : "false");
    1687       12952 : }
    1688       12952 : 
    1689             : void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
    1690             :   if (!Flags)
    1691       11506 :     return;
    1692             : 
    1693         607 :   Out << FS << Name << ": ";
    1694         607 : 
    1695             :   SmallVector<DINode::DIFlags, 8> SplitFlags;
    1696             :   auto Extra = DINode::splitFlags(Flags, SplitFlags);
    1697         698 : 
    1698             :   FieldSeparator FlagsFS(" | ");
    1699       66134 :   for (auto F : SplitFlags) {
    1700       66134 :     auto StringF = DINode::getFlagString(F);
    1701             :     assert(!StringF.empty() && "Expected valid flag");
    1702             :     Out << FlagsFS << StringF;
    1703       73022 :   }
    1704             :   if (Extra || SplitFlags.empty())
    1705             :     Out << FlagsFS << Extra;
    1706       29778 : }
    1707             : 
    1708       29778 : void MDFieldPrinter::printEmissionKind(StringRef Name,
    1709             :                                        DICompileUnit::DebugEmissionKind EK) {
    1710       39889 :   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
    1711             : }
    1712             : 
    1713       17920 : void MDFieldPrinter::printNameTableKind(StringRef Name,
    1714       17920 :                                         DICompileUnit::DebugNameTableKind NTK) {
    1715       10385 :   if (NTK == DICompileUnit::DebugNameTableKind::Default)
    1716             :     return;
    1717       15070 :   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
    1718             : }
    1719             : 
    1720        7535 : template <class IntTy, class Stringifier>
    1721             : void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
    1722             :                                     Stringifier toString, bool ShouldSkipZero) {
    1723       17308 :   if (!Value)
    1724        9773 :     return;
    1725             : 
    1726       12011 :   Out << FS << Name << ": ";
    1727             :   auto S = toString(Value);
    1728        7535 :   if (!S.empty())
    1729           0 :     Out << S;
    1730             :   else
    1731             :     Out << Value;
    1732        1178 : }
    1733             : 
    1734        2356 : static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
    1735        1178 :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1736             :                                const Module *Context) {
    1737        1178 :   Out << "!GenericDINode(";
    1738             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1739        1178 :   Printer.printTag(N);
    1740             :   Printer.printString("header", N->getHeader());
    1741         940 :   if (N->getNumDwarfOperands()) {
    1742             :     Out << Printer.FS << "operands: {";
    1743             :     FieldSeparator IFS;
    1744             :     for (auto &I : N->dwarf_operands()) {
    1745       10312 :       Out << IFS;
    1746             :       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
    1747       10312 :     }
    1748        7686 :     Out << "}";
    1749             :   }
    1750        5252 :   Out << ")";
    1751        2626 : }
    1752        2626 : 
    1753        2626 : static void writeDILocation(raw_ostream &Out, const DILocation *DL,
    1754             :                             TypePrinting *TypePrinter, SlotTracker *Machine,
    1755           0 :                             const Module *Context) {
    1756             :   Out << "!DILocation(";
    1757        2068 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1758             :   // Always output the line, since 0 is a relevant and important value for it.
    1759        2068 :   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
    1760        1966 :   Printer.printInt("column", DL->getColumn());
    1761             :   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
    1762         204 :   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
    1763         102 :   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
    1764         102 :                     /* Default */ false);
    1765         102 :   Out << ")";
    1766             : }
    1767           0 : 
    1768             : static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
    1769        8244 :                             TypePrinting *TypePrinter, SlotTracker *Machine,
    1770             :                             const Module *Context) {
    1771        8244 :   Out << "!DISubrange(";
    1772        5720 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1773             :   if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
    1774        5048 :     Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
    1775        2524 :   else
    1776        2524 :     Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
    1777        2524 :                           /*ShouldSkipNull */ false);
    1778             :   Printer.printInt("lowerBound", N->getLowerBound());
    1779           0 :   Out << ")";
    1780             : }
    1781             : 
    1782          20 : static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
    1783             :                               TypePrinting *, SlotTracker *, const Module *) {
    1784             :   Out << "!DIEnumerator(";
    1785          20 :   MDFieldPrinter Printer(Out);
    1786             :   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
    1787          20 :   if (N->isUnsigned()) {
    1788          20 :     auto Value = static_cast<uint64_t>(N->getValue());
    1789          20 :     Printer.printInt("value", Value, /* ShouldSkipZero */ false);
    1790           5 :     Printer.printBool("isUnsigned", true);
    1791             :   } else {
    1792          20 :     Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
    1793             :   }
    1794          15 :   Out << ")";
    1795             : }
    1796           5 : 
    1797             : static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
    1798          20 :                              TypePrinting *, SlotTracker *, const Module *) {
    1799          20 :   Out << "!DIBasicType(";
    1800             :   MDFieldPrinter Printer(Out);
    1801       12003 :   if (N->getTag() != dwarf::DW_TAG_base_type)
    1802             :     Printer.printTag(N);
    1803             :   Printer.printString("name", N->getName());
    1804       12003 :   Printer.printInt("size", N->getSizeInBits());
    1805             :   Printer.printInt("align", N->getAlignInBits());
    1806             :   Printer.printDwarfEnum("encoding", N->getEncoding(),
    1807       24006 :                          dwarf::AttributeEncodingString);
    1808       24006 :   Printer.printDIFlags("flags", N->getFlags());
    1809       12003 :   Out << ")";
    1810       12003 : }
    1811       24006 : 
    1812             : static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
    1813       12003 :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1814       12003 :                                const Module *Context) {
    1815             :   Out << "!DIDerivedType(";
    1816         285 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1817             :   Printer.printTag(N);
    1818             :   Printer.printString("name", N->getName());
    1819         285 :   Printer.printMetadata("scope", N->getRawScope());
    1820             :   Printer.printMetadata("file", N->getRawFile());
    1821         266 :   Printer.printInt("line", N->getLine());
    1822         265 :   Printer.printMetadata("baseType", N->getRawBaseType(),
    1823             :                         /* ShouldSkipNull */ false);
    1824          20 :   Printer.printInt("size", N->getSizeInBits());
    1825             :   Printer.printInt("align", N->getAlignInBits());
    1826         570 :   Printer.printInt("offset", N->getOffsetInBits());
    1827         285 :   Printer.printDIFlags("flags", N->getFlags());
    1828         285 :   Printer.printMetadata("extraData", N->getRawExtraData());
    1829             :   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
    1830           0 :     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
    1831             :                      /* ShouldSkipZero */ false);
    1832           0 :   Out << ")";
    1833             : }
    1834           0 : 
    1835           0 : static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
    1836           0 :                                  TypePrinting *TypePrinter,
    1837           0 :                                  SlotTracker *Machine, const Module *Context) {
    1838           0 :   Out << "!DICompositeType(";
    1839             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1840           0 :   Printer.printTag(N);
    1841             :   Printer.printString("name", N->getName());
    1842           0 :   Printer.printMetadata("scope", N->getRawScope());
    1843           0 :   Printer.printMetadata("file", N->getRawFile());
    1844             :   Printer.printInt("line", N->getLine());
    1845           0 :   Printer.printMetadata("baseType", N->getRawBaseType());
    1846             :   Printer.printInt("size", N->getSizeInBits());
    1847           0 :   Printer.printInt("align", N->getAlignInBits());
    1848             :   Printer.printInt("offset", N->getOffsetInBits());
    1849           0 :   Printer.printDIFlags("flags", N->getFlags());
    1850           0 :   Printer.printMetadata("elements", N->getRawElements());
    1851           0 :   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
    1852           0 :                          dwarf::LanguageString);
    1853           0 :   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
    1854           0 :   Printer.printMetadata("templateParams", N->getRawTemplateParams());
    1855             :   Printer.printString("identifier", N->getIdentifier());
    1856           0 :   Printer.printMetadata("discriminator", N->getRawDiscriminator());
    1857           0 :   Out << ")";
    1858           0 : }
    1859             : 
    1860        3621 : static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
    1861             :                                   TypePrinting *TypePrinter,
    1862             :                                   SlotTracker *Machine, const Module *Context) {
    1863        3621 :   Out << "!DISubroutineType(";
    1864             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1865        3621 :   Printer.printDIFlags("flags", N->getFlags());
    1866        3621 :   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
    1867        3621 :   Printer.printMetadata("types", N->getRawTypeArray(),
    1868        3621 :                         /* ShouldSkipNull */ false);
    1869        7242 :   Out << ")";
    1870        3621 : }
    1871             : 
    1872        7242 : static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
    1873        7242 :                         SlotTracker *, const Module *) {
    1874        7242 :   Out << "!DIFile(";
    1875        7242 :   MDFieldPrinter Printer(Out);
    1876        3621 :   Printer.printString("filename", N->getFilename(),
    1877        3621 :                       /* ShouldSkipEmpty */ false);
    1878          27 :   Printer.printString("directory", N->getDirectory(),
    1879             :                       /* ShouldSkipEmpty */ false);
    1880        3621 :   // Print all values for checksum together, or not at all.
    1881        3621 :   if (N->getChecksum())
    1882             :     Printer.printChecksum(*N->getChecksum());
    1883        1674 :   Printer.printString("source", N->getSource().getValueOr(StringRef()),
    1884             :                       /* ShouldSkipEmpty */ true);
    1885             :   Out << ")";
    1886        1674 : }
    1887             : 
    1888        1674 : static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
    1889        1674 :                                TypePrinting *TypePrinter, SlotTracker *Machine,
    1890        1674 :                                const Module *Context) {
    1891        1674 :   Out << "!DICompileUnit(";
    1892        3348 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1893        1674 :   Printer.printDwarfEnum("language", N->getSourceLanguage(),
    1894        3348 :                          dwarf::LanguageString, /* ShouldSkipZero */ false);
    1895        3348 :   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
    1896        3348 :   Printer.printString("producer", N->getProducer());
    1897        3348 :   Printer.printBool("isOptimized", N->isOptimized());
    1898        1674 :   Printer.printString("flags", N->getFlags());
    1899        3348 :   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
    1900             :                    /* ShouldSkipZero */ false);
    1901        1674 :   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
    1902        1674 :   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
    1903        1674 :   Printer.printMetadata("enums", N->getRawEnumTypes());
    1904        1674 :   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
    1905        1674 :   Printer.printMetadata("globals", N->getRawGlobalVariables());
    1906        1674 :   Printer.printMetadata("imports", N->getRawImportedEntities());
    1907             :   Printer.printMetadata("macros", N->getRawMacros());
    1908        2068 :   Printer.printInt("dwoId", N->getDWOId());
    1909             :   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
    1910             :   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
    1911        2068 :                     false);
    1912             :   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
    1913        4136 :   Out << ")";
    1914        4136 : }
    1915        2068 : 
    1916             : static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
    1917        2068 :                               TypePrinting *TypePrinter, SlotTracker *Machine,
    1918        2068 :                               const Module *Context) {
    1919             :   Out << "!DISubprogram(";
    1920           0 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1921             :   Printer.printString("name", N->getName());
    1922           0 :   Printer.printString("linkageName", N->getLinkageName());
    1923             :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1924           0 :   Printer.printMetadata("file", N->getRawFile());
    1925             :   Printer.printInt("line", N->getLine());
    1926           0 :   Printer.printMetadata("type", N->getRawType());
    1927             :   Printer.printBool("isLocal", N->isLocalToUnit());
    1928             :   Printer.printBool("isDefinition", N->isDefinition());
    1929           0 :   Printer.printInt("scopeLine", N->getScopeLine());
    1930           0 :   Printer.printMetadata("containingType", N->getRawContainingType());
    1931           0 :   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
    1932             :                          dwarf::VirtualityString);
    1933           0 :   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
    1934           0 :       N->getVirtualIndex() != 0)
    1935             :     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
    1936        1178 :   Printer.printInt("thisAdjustment", N->getThisAdjustment());
    1937             :   Printer.printDIFlags("flags", N->getFlags());
    1938             :   Printer.printBool("isOptimized", N->isOptimized());
    1939        1178 :   Printer.printMetadata("unit", N->getRawUnit());
    1940             :   Printer.printMetadata("templateParams", N->getRawTemplateParams());
    1941        2356 :   Printer.printMetadata("declaration", N->getRawDeclaration());
    1942             :   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
    1943        1178 :   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
    1944        1178 :   Out << ")";
    1945        2356 : }
    1946        1178 : 
    1947        2356 : static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
    1948             :                                 TypePrinting *TypePrinter, SlotTracker *Machine,
    1949        1178 :                                 const Module *Context) {
    1950        2356 :   Out << "!DILexicalBlock(";
    1951        1178 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1952        1178 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1953        1178 :   Printer.printMetadata("file", N->getRawFile());
    1954        1178 :   Printer.printInt("line", N->getLine());
    1955        1178 :   Printer.printInt("column", N->getColumn());
    1956        2356 :   Out << ")";
    1957        2356 : }
    1958        2356 : 
    1959             : static void writeDILexicalBlockFile(raw_ostream &Out,
    1960        2356 :                                     const DILexicalBlockFile *N,
    1961        1178 :                                     TypePrinting *TypePrinter,
    1962        1178 :                                     SlotTracker *Machine,
    1963             :                                     const Module *Context) {
    1964        4239 :   Out << "!DILexicalBlockFile(";
    1965             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1966             :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1967        4239 :   Printer.printMetadata("file", N->getRawFile());
    1968             :   Printer.printInt("discriminator", N->getDiscriminator(),
    1969        4239 :                    /* ShouldSkipZero */ false);
    1970        4239 :   Out << ")";
    1971        4239 : }
    1972        4239 : 
    1973        8478 : static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
    1974        4239 :                              TypePrinting *TypePrinter, SlotTracker *Machine,
    1975        8478 :                              const Module *Context) {
    1976        8478 :   Out << "!DINamespace(";
    1977        8478 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1978        4239 :   Printer.printString("name", N->getName());
    1979        4239 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    1980             :   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
    1981        4239 :   Out << ")";
    1982        4144 : }
    1983         524 : 
    1984        8478 : static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
    1985        8478 :                          TypePrinting *TypePrinter, SlotTracker *Machine,
    1986        8478 :                          const Module *Context) {
    1987        4239 :   Out << "!DIMacro(";
    1988        4239 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    1989        4239 :   Printer.printMacinfoType(N);
    1990        4239 :   Printer.printInt("line", N->getLine());
    1991        4239 :   Printer.printString("name", N->getName());
    1992        4239 :   Printer.printString("value", N->getValue());
    1993        4239 :   Out << ")";
    1994             : }
    1995         840 : 
    1996             : static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
    1997             :                              TypePrinting *TypePrinter, SlotTracker *Machine,
    1998         840 :                              const Module *Context) {
    1999             :   Out << "!DIMacroFile(";
    2000         840 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2001         840 :   Printer.printInt("line", N->getLine());
    2002        1680 :   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
    2003        1680 :   Printer.printMetadata("nodes", N->getRawElements());
    2004         840 :   Out << ")";
    2005         840 : }
    2006             : 
    2007         256 : static void writeDIModule(raw_ostream &Out, const DIModule *N,
    2008             :                           TypePrinting *TypePrinter, SlotTracker *Machine,
    2009             :                           const Module *Context) {
    2010             :   Out << "!DIModule(";
    2011             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2012         256 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    2013             :   Printer.printString("name", N->getName());
    2014         256 :   Printer.printString("configMacros", N->getConfigurationMacros());
    2015         256 :   Printer.printString("includePath", N->getIncludePath());
    2016         512 :   Printer.printString("isysroot", N->getISysRoot());
    2017             :   Out << ")";
    2018         256 : }
    2019         256 : 
    2020             : 
    2021         143 : static void writeDITemplateTypeParameter(raw_ostream &Out,
    2022             :                                          const DITemplateTypeParameter *N,
    2023             :                                          TypePrinting *TypePrinter,
    2024         143 :                                          SlotTracker *Machine,
    2025             :                                          const Module *Context) {
    2026         143 :   Out << "!DITemplateTypeParameter(";
    2027         143 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2028         286 :   Printer.printString("name", N->getName());
    2029         143 :   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
    2030         143 :   Out << ")";
    2031             : }
    2032        1427 : 
    2033             : static void writeDITemplateValueParameter(raw_ostream &Out,
    2034             :                                           const DITemplateValueParameter *N,
    2035        1427 :                                           TypePrinting *TypePrinter,
    2036             :                                           SlotTracker *Machine,
    2037        1427 :                                           const Module *Context) {
    2038        2854 :   Out << "!DITemplateValueParameter(";
    2039        1427 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2040        1427 :   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
    2041        1427 :     Printer.printTag(N);
    2042        1427 :   Printer.printString("name", N->getName());
    2043             :   Printer.printMetadata("type", N->getRawType());
    2044          39 :   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
    2045             :   Out << ")";
    2046             : }
    2047          39 : 
    2048             : static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
    2049          78 :                                   TypePrinting *TypePrinter,
    2050          39 :                                   SlotTracker *Machine, const Module *Context) {
    2051          39 :   Out << "!DIGlobalVariable(";
    2052          39 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2053          39 :   Printer.printString("name", N->getName());
    2054             :   Printer.printString("linkageName", N->getLinkageName());
    2055          39 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    2056             :   Printer.printMetadata("file", N->getRawFile());
    2057             :   Printer.printInt("line", N->getLine());
    2058          39 :   Printer.printMetadata("type", N->getRawType());
    2059             :   Printer.printBool("isLocal", N->isLocalToUnit());
    2060          39 :   Printer.printBool("isDefinition", N->isDefinition());
    2061          39 :   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
    2062          39 :   Printer.printMetadata("templateParams", N->getRawTemplateParams());
    2063          39 :   Printer.printInt("align", N->getAlignInBits());
    2064          39 :   Out << ")";
    2065          39 : }
    2066          39 : 
    2067             : static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
    2068             :                                  TypePrinting *TypePrinter,
    2069         163 :                                  SlotTracker *Machine, const Module *Context) {
    2070             :   Out << "!DILocalVariable(";
    2071             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2072             :   Printer.printString("name", N->getName());
    2073             :   Printer.printInt("arg", N->getArg());
    2074         163 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    2075             :   Printer.printMetadata("file", N->getRawFile());
    2076         163 :   Printer.printInt("line", N->getLine());
    2077         163 :   Printer.printMetadata("type", N->getRawType());
    2078         163 :   Printer.printDIFlags("flags", N->getFlags());
    2079         163 :   Printer.printInt("align", N->getAlignInBits());
    2080             :   Out << ")";
    2081         271 : }
    2082             : 
    2083             : static void writeDILabel(raw_ostream &Out, const DILabel *N,
    2084             :                          TypePrinting *TypePrinter,
    2085             :                          SlotTracker *Machine, const Module *Context) {
    2086         271 :   Out << "!DILabel(";
    2087             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2088         271 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    2089          13 :   Printer.printString("name", N->getName());
    2090         271 :   Printer.printMetadata("file", N->getRawFile());
    2091         271 :   Printer.printInt("line", N->getLine());
    2092         271 :   Out << ")";
    2093         271 : }
    2094         271 : 
    2095             : static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
    2096         675 :                               TypePrinting *TypePrinter, SlotTracker *Machine,
    2097             :                               const Module *Context) {
    2098             :   Out << "!DIExpression(";
    2099         675 :   FieldSeparator FS;
    2100             :   if (N->isValid()) {
    2101         675 :     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
    2102         675 :       auto OpStr = dwarf::OperationEncodingString(I->getOp());
    2103         675 :       assert(!OpStr.empty() && "Expected valid opcode");
    2104         675 : 
    2105        1350 :       Out << FS << OpStr;
    2106         675 :       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
    2107        1350 :         Out << FS << I->getArg(A);
    2108        1350 :     }
    2109         675 :   } else {
    2110         675 :     for (const auto &I : N->getElements())
    2111        1350 :       Out << FS << I;
    2112         675 :   }
    2113         675 :   Out << ")";
    2114             : }
    2115        5165 : 
    2116             : static void writeDIGlobalVariableExpression(raw_ostream &Out,
    2117             :                                             const DIGlobalVariableExpression *N,
    2118        5165 :                                             TypePrinting *TypePrinter,
    2119             :                                             SlotTracker *Machine,
    2120        5165 :                                             const Module *Context) {
    2121        5165 :   Out << "!DIGlobalVariableExpression(";
    2122        5165 :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2123        5165 :   Printer.printMetadata("var", N->getVariable());
    2124       10330 :   Printer.printMetadata("expr", N->getExpression());
    2125        5165 :   Out << ")";
    2126       10330 : }
    2127       10330 : 
    2128        5165 : static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
    2129        5165 :                                 TypePrinting *TypePrinter, SlotTracker *Machine,
    2130             :                                 const Module *Context) {
    2131          13 :   Out << "!DIObjCProperty(";
    2132             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2133             :   Printer.printString("name", N->getName());
    2134          13 :   Printer.printMetadata("file", N->getRawFile());
    2135             :   Printer.printInt("line", N->getLine());
    2136          13 :   Printer.printString("setter", N->getSetterName());
    2137          13 :   Printer.printString("getter", N->getGetterName());
    2138          13 :   Printer.printInt("attributes", N->getAttributes());
    2139          26 :   Printer.printMetadata("type", N->getRawType());
    2140          13 :   Out << ")";
    2141          13 : }
    2142             : 
    2143           0 : static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
    2144             :                                   TypePrinting *TypePrinter,
    2145             :                                   SlotTracker *Machine, const Module *Context) {
    2146           0 :   Out << "!DIImportedEntity(";
    2147             :   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
    2148           0 :   Printer.printTag(N);
    2149           0 :   Printer.printString("name", N->getName());
    2150           0 :   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
    2151             :   Printer.printMetadata("entity", N->getRawEntity());
    2152             :   Printer.printMetadata("file", N->getRawFile());
    2153           0 :   Printer.printInt("line", N->getLine());
    2154           0 :   Out << ")";
    2155           0 : }
    2156             : 
    2157             : static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
    2158           0 :                                     TypePrinting *TypePrinter,
    2159           0 :                                     SlotTracker *Machine,
    2160             :                                     const Module *Context) {
    2161           0 :   if (Node->isDistinct())
    2162           0 :     Out << "distinct ";
    2163             :   else if (Node->isTemporary())
    2164         657 :     Out << "<temporary!> "; // Handle broken code.
    2165             : 
    2166             :   switch (Node->getMetadataID()) {
    2167             :   default:
    2168             :     llvm_unreachable("Expected uniquable MDNode");
    2169         657 : #define HANDLE_MDNODE_LEAF(CLASS)                                              \
    2170             :   case Metadata::CLASS##Kind:                                                  \
    2171         657 :     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
    2172         657 :     break;
    2173         657 : #include "llvm/IR/Metadata.def"
    2174         657 :   }
    2175             : }
    2176          52 : 
    2177             : // Full implementation of printing a Value as an operand with support for
    2178             : // TypePrinting, etc.
    2179          52 : static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
    2180             :                                    TypePrinting *TypePrinter,
    2181          52 :                                    SlotTracker *Machine,
    2182          52 :                                    const Module *Context) {
    2183         104 :   if (V->hasName()) {
    2184          52 :     PrintLLVMName(Out, V);
    2185          52 :     return;
    2186         104 :   }
    2187          52 : 
    2188          52 :   const Constant *CV = dyn_cast<Constant>(V);
    2189          52 :   if (CV && !isa<GlobalValue>(CV)) {
    2190             :     assert(TypePrinter && "Constants require TypePrinting!");
    2191          76 :     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
    2192             :     return;
    2193             :   }
    2194          76 : 
    2195             :   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    2196          76 :     Out << "asm ";
    2197          76 :     if (IA->hasSideEffects())
    2198          76 :       Out << "sideeffect ";
    2199          76 :     if (IA->isAlignStack())
    2200          76 :       Out << "alignstack ";
    2201         152 :     // We don't emit the AD_ATT dialect as it's the assumed default.
    2202          76 :     if (IA->getDialect() == InlineAsm::AD_Intel)
    2203          76 :       Out << "inteldialect ";
    2204             :     Out << '"';
    2205      102896 :     printEscapedString(IA->getAsmString(), Out);
    2206             :     Out << "\", \"";
    2207             :     printEscapedString(IA->getConstraintString(), Out);
    2208             :     Out << '"';
    2209      102896 :     return;
    2210       19912 :   }
    2211       82984 : 
    2212           1 :   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
    2213             :     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
    2214      205792 :                            Context, /* FromValue */ true);
    2215           0 :     return;
    2216           0 :   }
    2217             : 
    2218             :   char Prefix = '%';
    2219             :   int Slot;
    2220             :   // If we have a SlotTracker, use it.
    2221             :   if (Machine) {
    2222             :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    2223      102896 :       Slot = Machine->getGlobalSlot(GV);
    2224             :       Prefix = '@';
    2225             :     } else {
    2226             :       Slot = Machine->getLocalSlot(V);
    2227     5112794 : 
    2228             :       // If the local value didn't succeed, then we may be referring to a value
    2229             :       // from a different function.  Translate it, as this can happen when using
    2230             :       // address of blocks.
    2231     5112794 :       if (Slot == -1)
    2232     2984738 :         if ((Machine = createSlotTracker(V))) {
    2233     2984738 :           Slot = Machine->getLocalSlot(V);
    2234             :           delete Machine;
    2235             :         }
    2236             :     }
    2237             :   } else if ((Machine = createSlotTracker(V))) {
    2238             :     // Otherwise, create one to get the # and then destroy it.
    2239     1309596 :     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
    2240     1309596 :       Slot = Machine->getGlobalSlot(GV);
    2241             :       Prefix = '@';
    2242             :     } else {
    2243             :       Slot = Machine->getLocalSlot(V);
    2244        2285 :     }
    2245        2285 :     delete Machine;
    2246        1534 :     Machine = nullptr;
    2247        2285 :   } else {
    2248          10 :     Slot = -1;
    2249             :   }
    2250        2285 : 
    2251         149 :   if (Slot != -1)
    2252             :     Out << Prefix << Slot;
    2253        2285 :   else
    2254        2285 :     Out << "<badref>";
    2255        2285 : }
    2256             : 
    2257        2285 : static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
    2258             :                                    TypePrinting *TypePrinter,
    2259             :                                    SlotTracker *Machine, const Module *Context,
    2260             :                                    bool FromValue) {
    2261       16765 :   // Write DIExpressions inline when used as a value. Improves readability of
    2262             :   // debug info intrinsics.
    2263       16765 :   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
    2264             :     writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
    2265             :     return;
    2266             :   }
    2267             : 
    2268             :   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
    2269      799410 :     std::unique_ptr<SlotTracker> MachineStorage;
    2270             :     if (!Machine) {
    2271       29909 :       MachineStorage = make_unique<SlotTracker>(Context);
    2272             :       Machine = MachineStorage.get();
    2273             :     }
    2274      769130 :     int Slot = Machine->getMetadataSlot(N);
    2275             :     if (Slot == -1)
    2276             :       // Give the pointer value instead of "badref", since this comes up all
    2277             :       // the time when debugging.
    2278             :       Out << "<" << N << ">";
    2279      769130 :     else
    2280        1019 :       Out << '!' << Slot;
    2281        1019 :     return;
    2282        1019 :   }
    2283             : 
    2284             :   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
    2285         371 :     Out << "!\"";
    2286             :     printEscapedString(MDS->getString(), Out);
    2287             :     Out << '"';
    2288          29 :     return;
    2289             :   }
    2290             : 
    2291         342 :   auto *V = cast<ValueAsMetadata>(MD);
    2292             :   assert(TypePrinter && "TypePrinter required for metadata values");
    2293         371 :   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
    2294             :          "Unexpected function-local metadata outside of value argument");
    2295             : 
    2296             :   TypePrinter->print(V->getValue()->getType(), Out);
    2297             :   Out << ' ';
    2298             :   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
    2299      799410 : }
    2300             : 
    2301             : namespace {
    2302           2 : 
    2303             : class AssemblyWriter {
    2304             :   formatted_raw_ostream &Out;
    2305      329017 :   const Module *TheModule = nullptr;
    2306             :   const ModuleSummaryIndex *TheIndex = nullptr;
    2307             :   std::unique_ptr<SlotTracker> SlotTrackerStorage;
    2308             :   SlotTracker &Machine;
    2309             :   TypePrinting TypePrinter;
    2310             :   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
    2311             :   SetVector<const Comdat *> Comdats;
    2312        7645 :   bool IsForDebug;
    2313        7645 :   bool ShouldPreserveUseListOrder;
    2314             :   UseListOrderStack UseListOrders;
    2315             :   SmallVector<StringRef, 8> MDNames;
    2316             :   /// Synchronization scope names registered with LLVMContext.
    2317      270450 :   SmallVector<StringRef, 8> SSNs;
    2318      270450 :   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
    2319           5 : 
    2320             : public:
    2321             :   /// Construct an AssemblyWriter with an external SlotTracker
    2322      270450 :   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
    2323      270450 :                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
    2324             :                  bool ShouldPreserveUseListOrder = false);
    2325             : 
    2326          25 :   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
    2327             :                  const ModuleSummaryIndex *Index, bool IsForDebug);
    2328             : 
    2329             :   void printMDNodeBody(const MDNode *MD);
    2330             :   void printNamedMDNode(const NamedMDNode *NMD);
    2331             : 
    2332             :   void printModule(const Module *M);
    2333       45089 : 
    2334       45089 :   void writeOperand(const Value *Op, bool PrintType);
    2335             :   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
    2336       45089 :   void writeOperandBundles(ImmutableCallSite CS);
    2337             :   void writeSyncScope(const LLVMContext &Context,
    2338             :                       SyncScope::ID SSID);
    2339             :   void writeAtomic(const LLVMContext &Context,
    2340             :                    AtomicOrdering Ordering,
    2341             :                    SyncScope::ID SSID);
    2342             :   void writeAtomicCmpXchg(const LLVMContext &Context,
    2343             :                           AtomicOrdering SuccessOrdering,
    2344        5833 :                           AtomicOrdering FailureOrdering,
    2345             :                           SyncScope::ID SSID);
    2346        5833 : 
    2347             :   void writeAllMDNodes();
    2348             :   void writeMDNode(unsigned Slot, const MDNode *Node);
    2349             :   void writeAllAttributeGroups();
    2350             : 
    2351             :   void printTypeIdentities();
    2352             :   void printGlobal(const GlobalVariable *GV);
    2353             :   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
    2354             :   void printComdat(const Comdat *C);
    2355             :   void printFunction(const Function *F);
    2356             :   void printArgument(const Argument *FA, AttributeSet Attrs);
    2357             :   void printBasicBlock(const BasicBlock *BB);
    2358             :   void printInstructionLine(const Instruction &I);
    2359             :   void printInstruction(const Instruction &I);
    2360             : 
    2361             :   void printUseListOrder(const UseListOrder &Order);
    2362             :   void printUseLists(const Function *F);
    2363             : 
    2364             :   void printModuleSummaryIndex();
    2365             :   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
    2366             :   void printSummary(const GlobalValueSummary &Summary);
    2367             :   void printAliasSummary(const AliasSummary *AS);
    2368             :   void printGlobalVarSummary(const GlobalVarSummary *GS);
    2369             :   void printFunctionSummary(const FunctionSummary *FS);
    2370             :   void printTypeIdSummary(const TypeIdSummary &TIS);
    2371             :   void printTypeTestResolution(const TypeTestResolution &TTRes);
    2372             :   void printArgs(const std::vector<uint64_t> &Args);
    2373             :   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
    2374             :   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
    2375             :   void printVFuncId(const FunctionSummary::VFuncId VFId);
    2376             :   void
    2377             :   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
    2378             :                       const char *Tag);
    2379             :   void
    2380             :   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
    2381             :                    const char *Tag);
    2382             : 
    2383             : private:
    2384             :   /// Print out metadata attachments.
    2385             :   void printMetadataAttachments(
    2386             :       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
    2387             :       StringRef Separator);
    2388             : 
    2389             :   // printInfoComment - Print a little comment after the instruction indicating
    2390             :   // which slot it occupies.
    2391             :   void printInfoComment(const Value &V);
    2392             : 
    2393             :   // printGCRelocateComment - print comment after call to the gc.relocate
    2394             :   // intrinsic indicating base and derived pointer names.
    2395             :   void printGCRelocateComment(const GCRelocateInst &Relocate);
    2396             : };
    2397             : 
    2398             : } // end anonymous namespace
    2399             : 
    2400             : AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
    2401             :                                const Module *M, AssemblyAnnotationWriter *AAW,
    2402             :                                bool IsForDebug, bool ShouldPreserveUseListOrder)
    2403             :     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
    2404             :       IsForDebug(IsForDebug),
    2405             :       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
    2406             :   if (!TheModule)
    2407             :     return;
    2408             :   for (const GlobalObject &GO : TheModule->global_objects())
    2409             :     if (const Comdat *C = GO.getComdat())
    2410             :       Comdats.insert(C);
    2411             : }
    2412             : 
    2413             : AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
    2414             :                                const ModuleSummaryIndex *Index, bool IsForDebug)
    2415             :     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
    2416             :       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
    2417             : 
    2418             : void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
    2419             :   if (!Operand) {
    2420             :     Out << "<null operand!>";
    2421             :     return;
    2422             :   }
    2423             :   if (PrintType) {
    2424             :     TypePrinter.print(Operand->getType(), Out);
    2425             :     Out << ' ';
    2426             :   }
    2427             :   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
    2428             : }
    2429             : 
    2430             : void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
    2431             :                                     SyncScope::ID SSID) {
    2432             :   switch (SSID) {
    2433             :   case SyncScope::System: {
    2434             :     break;
    2435             :   }
    2436             :   default: {
    2437             :     if (SSNs.empty())
    2438             :       Context.getSyncScopeNames(SSNs);
    2439             : 
    2440             :     Out << " syncscope(\"";
    2441             :     printEscapedString(SSNs[SSID], Out);
    2442             :     Out << "\")";
    2443             :     break;
    2444             :   }
    2445             :   }
    2446             : }
    2447             : 
    2448       52932 : void AssemblyWriter::writeAtomic(const LLVMContext &Context,
    2449             :                                  AtomicOrdering Ordering,
    2450       52932 :                                  SyncScope::ID SSID) {
    2451             :   if (Ordering == AtomicOrdering::NotAtomic)
    2452             :     return;
    2453      158796 : 
    2454       52932 :   writeSyncScope(Context, SSID);
    2455             :   Out << " " << toIRString(Ordering);
    2456             : }
    2457     1402969 : 
    2458       28710 : void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
    2459             :                                         AtomicOrdering SuccessOrdering,
    2460             :                                         AtomicOrdering FailureOrdering,
    2461          69 :                                         SyncScope::ID SSID) {
    2462          69 :   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
    2463             :          FailureOrdering != AtomicOrdering::NotAtomic);
    2464         207 : 
    2465             :   writeSyncScope(Context, SSID);
    2466     3398972 :   Out << " " << toIRString(SuccessOrdering);
    2467     3398972 :   Out << " " << toIRString(FailureOrdering);
    2468           0 : }
    2469           0 : 
    2470             : void AssemblyWriter::writeParamOperand(const Value *Operand,
    2471     3398972 :                                        AttributeSet Attrs) {
    2472     1817283 :   if (!Operand) {
    2473     1817283 :     Out << "<null operand!>";
    2474             :     return;
    2475     3398972 :   }
    2476             : 
    2477             :   // Print the type
    2478        3746 :   TypePrinter.print(Operand->getType(), Out);
    2479             :   // Print parameter attributes list
    2480        3746 :   if (Attrs.hasAttributes())
    2481             :     Out << ' ' << Attrs.getAsString();
    2482             :   Out << ' ';
    2483             :   // Print the operand
    2484         424 :   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
    2485         424 : }
    2486          39 : 
    2487             : void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
    2488         424 :   if (!CS.hasOperandBundles())
    2489         848 :     return;
    2490         424 : 
    2491         424 :   Out << " [ ";
    2492             : 
    2493             :   bool FirstBundle = true;
    2494        3746 :   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
    2495             :     OperandBundleUse BU = CS.getOperandBundleAt(i);
    2496        3037 : 
    2497             :     if (!FirstBundle)
    2498             :       Out << ", ";
    2499        3037 :     FirstBundle = false;
    2500             : 
    2501             :     Out << '"';
    2502        3037 :     printEscapedString(BU.getTagName(), Out);
    2503        3037 :     Out << '"';
    2504             : 
    2505             :     Out << '(';
    2506         709 : 
    2507             :     bool FirstInput = true;
    2508             :     for (const auto &Input : BU.Inputs) {
    2509             :       if (!FirstInput)
    2510             :         Out << ", ";
    2511             :       FirstInput = false;
    2512             : 
    2513         709 :       TypePrinter.print(Input->getType(), Out);
    2514         709 :       Out << " ";
    2515         709 :       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
    2516         709 :     }
    2517             : 
    2518      406376 :     Out << ')';
    2519             :   }
    2520      406376 : 
    2521           0 :   Out << " ]";
    2522           0 : }
    2523             : 
    2524             : void AssemblyWriter::printModule(const Module *M) {
    2525             :   Machine.initializeIfNeeded();
    2526      406376 : 
    2527             :   if (ShouldPreserveUseListOrder)
    2528      406376 :     UseListOrders = predictUseListOrder(M);
    2529       83880 : 
    2530      406376 :   if (!M->getModuleIdentifier().empty() &&
    2531             :       // Don't print the ID if it will start a new line (which would
    2532      406376 :       // require a comment char before it).
    2533             :       M->getModuleIdentifier().find('\n') == std::string::npos)
    2534             :     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
    2535      186508 : 
    2536      186508 :   if (!M->getSourceFileName().empty()) {
    2537             :     Out << "source_filename = \"";
    2538             :     printEscapedString(M->getSourceFileName(), Out);
    2539        1550 :     Out << "\"\n";
    2540             :   }
    2541             : 
    2542        3189 :   const std::string &DL = M->getDataLayoutStr();
    2543        1639 :   if (!DL.empty())
    2544             :     Out << "target datalayout = \"" << DL << "\"\n";
    2545        1639 :   if (!M->getTargetTriple().empty())
    2546          89 :     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
    2547             : 
    2548             :   if (!M->getModuleInlineAsm().empty()) {
    2549        1639 :     Out << '\n';
    2550        3278 : 
    2551        1639 :     // Split the string into lines, to make it easier to read the .ll file.
    2552             :     StringRef Asm = M->getModuleInlineAsm();
    2553        1639 :     do {
    2554             :       StringRef Front;
    2555             :       std::tie(Front, Asm) = Asm.split('\n');
    2556        2894 : 
    2557        1255 :       // We found a newline, print the portion of the asm string from the
    2558         338 :       // last newline up to this newline.
    2559             :       Out << "module asm \"";
    2560             :       printEscapedString(Front, Out);
    2561        1255 :       Out << "\"\n";
    2562        1255 :     } while (!Asm.empty());
    2563        1255 :   }
    2564             : 
    2565             :   printTypeIdentities();
    2566        1639 : 
    2567             :   // Output all comdats.
    2568             :   if (!Comdats.empty())
    2569        1550 :     Out << '\n';
    2570             :   for (const Comdat *C : Comdats) {
    2571             :     printComdat(C);
    2572       17389 :     if (C != Comdats.back())
    2573       17389 :       Out << '\n';
    2574             :   }
    2575       17389 : 
    2576         762 :   // Output all globals.
    2577             :   if (!M->global_empty()) Out << '\n';
    2578       34778 :   for (const GlobalVariable &GV : M->globals()) {
    2579             :     printGlobal(&GV); Out << '\n';
    2580             :   }
    2581       17389 : 
    2582       34778 :   // Output all aliases.
    2583             :   if (!M->alias_empty()) Out << "\n";
    2584       17389 :   for (const GlobalAlias &GA : M->aliases())
    2585       17389 :     printIndirectSymbol(&GA);
    2586       34778 : 
    2587       17389 :   // Output all ifuncs.
    2588             :   if (!M->ifunc_empty()) Out << "\n";
    2589             :   for (const GlobalIFunc &GI : M->ifuncs())
    2590             :     printIndirectSymbol(&GI);
    2591       17389 : 
    2592       24812 :   // Output global use-lists.
    2593       17389 :   printUseLists(nullptr);
    2594       23236 : 
    2595             :   // Output all of the functions.
    2596       17389 :   for (const Function &F : *M)
    2597         107 :     printFunction(&F);
    2598             :   assert(UseListOrders.empty() && "All use-lists should have been consumed");
    2599             : 
    2600             :   // Output all attribute groups.
    2601             :   if (!Machine.as_empty()) {
    2602             :     Out << '\n';
    2603         336 :     writeAllAttributeGroups();
    2604             :   }
    2605             : 
    2606             :   // Output named metadata.
    2607         336 :   if (!M->named_metadata_empty()) Out << '\n';
    2608         336 : 
    2609         336 :   for (const NamedMDNode &Node : M->named_metadata())
    2610         336 :     printNamedMDNode(&Node);
    2611             : 
    2612             :   // Output metadata.
    2613       17389 :   if (!Machine.mdn_empty()) {
    2614             :     Out << '\n';
    2615             :     writeAllMDNodes();
    2616       17389 :   }
    2617        2997 : }
    2618       42938 : 
    2619       25549 : void AssemblyWriter::printModuleSummaryIndex() {
    2620       25549 :   assert(TheIndex);
    2621       22552 :   Machine.initializeIndexIfNeeded();
    2622             : 
    2623             :   Out << "\n";
    2624             : 
    2625       17389 :   // Print module path entries. To print in order, add paths to a vector
    2626      102301 :   // indexed by module slot.
    2627       84912 :   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
    2628             :   std::string RegularLTOModuleName = "[Regular LTO]";
    2629             :   moduleVec.resize(TheIndex->modulePaths().size());
    2630             :   for (auto &ModPath : TheIndex->modulePaths())
    2631       17389 :     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
    2632       18583 :         // A module id of -1 is a special entry for a regular LTO module created
    2633        1194 :         // during the thin link.
    2634             :         ModPath.second.first == -1u ? RegularLTOModuleName
    2635             :                                     : (std::string)ModPath.first(),
    2636       17389 :         ModPath.second.second);
    2637       17470 : 
    2638          81 :   unsigned i = 0;
    2639             :   for (auto &ModPair : moduleVec) {
    2640             :     Out << "^" << i++ << " = module: (";
    2641       17389 :     Out << "path: \"";
    2642             :     printEscapedString(ModPair.first, Out);
    2643             :     Out << "\", hash: (";
    2644      226540 :     FieldSeparator FS;
    2645      209151 :     for (auto Hash : ModPair.second)
    2646             :       Out << FS << Hash;
    2647             :     Out << "))\n";
    2648             :   }
    2649       34778 : 
    2650       12197 :   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
    2651       12197 :   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
    2652             :   for (auto &GlobalList : *TheIndex) {
    2653             :     auto GUID = GlobalList.first;
    2654             :     for (auto &Summary : GlobalList.second.SummaryList)
    2655       17389 :       SummaryToGUIDMap[Summary.get()] = GUID;
    2656             :   }
    2657       37984 : 
    2658       20595 :   // Print the global value summary entries.
    2659             :   for (auto &GlobalList : *TheIndex) {
    2660             :     auto GUID = GlobalList.first;
    2661       34778 :     auto VI = TheIndex->getValueInfo(GlobalList);
    2662       10578 :     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
    2663       10578 :   }
    2664             : 
    2665       17389 :   // Print the TypeIdMap entries.
    2666             :   for (auto TidIter = TheIndex->typeIds().begin();
    2667          69 :        TidIter != TheIndex->typeIds().end(); TidIter++) {
    2668             :     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
    2669          69 :         << " = typeid: (name: \"" << TidIter->second.first << "\"";
    2670             :     printTypeIdSummary(TidIter->second.second);
    2671          69 :     Out << ") ; guid = " << TidIter->first << "\n";
    2672             :   }
    2673             : }
    2674             : 
    2675          69 : static const char *
    2676          69 : getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
    2677          69 :   switch (K) {
    2678         218 :   case WholeProgramDevirtResolution::Indir:
    2679         240 :     return "indir";
    2680             :   case WholeProgramDevirtResolution::SingleImpl:
    2681             :     return "singleImpl";
    2682         160 :   case WholeProgramDevirtResolution::BranchFunnel:
    2683             :     return "branchFunnel";
    2684             :   }
    2685             :   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
    2686             : }
    2687         149 : 
    2688          80 : static const char *getWholeProgDevirtResByArgKindName(
    2689          80 :     WholeProgramDevirtResolution::ByArg::Kind K) {
    2690         160 :   switch (K) {
    2691          80 :   case WholeProgramDevirtResolution::ByArg::Indir:
    2692             :     return "indir";
    2693         480 :   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
    2694         400 :     return "uniformRetVal";
    2695          80 :   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
    2696             :     return "uniqueRetVal";
    2697             :   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
    2698             :     return "virtualConstProp";
    2699             :   }
    2700         387 :   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
    2701         318 : }
    2702         542 : 
    2703         224 : static const char *getTTResKindName(TypeTestResolution::Kind K) {
    2704             :   switch (K) {
    2705             :   case TypeTestResolution::Unsat:
    2706             :     return "unsat";
    2707         387 :   case TypeTestResolution::ByteArray:
    2708         318 :     return "byteArray";
    2709         318 :   case TypeTestResolution::Inline:
    2710         318 :     return "inline";
    2711             :   case TypeTestResolution::Single:
    2712             :     return "single";
    2713             :   case TypeTestResolution::AllOnes:
    2714          69 :     return "allOnes";
    2715         170 :   }
    2716          16 :   llvm_unreachable("invalid TypeTestResolution kind");
    2717          32 : }
    2718          16 : 
    2719          16 : void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
    2720             :   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
    2721          69 :       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
    2722             : 
    2723             :   // The following fields are only used if the target does not support the use
    2724             :   // of absolute symbols to store constants. Print only if non-zero.
    2725           9 :   if (TTRes.AlignLog2)
    2726             :     Out << ", alignLog2: " << TTRes.AlignLog2;
    2727             :   if (TTRes.SizeM1)
    2728           4 :     Out << ", sizeM1: " << TTRes.SizeM1;
    2729             :   if (TTRes.BitMask)
    2730           4 :     // BitMask is uint8_t which causes it to print the corresponding char.
    2731             :     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
    2732             :   if (TTRes.InlineBits)
    2733           0 :     Out << ", inlineBits: " << TTRes.InlineBits;
    2734             : 
    2735             :   Out << ")";
    2736             : }
    2737             : 
    2738           4 : void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
    2739             :   Out << ", summary: (";
    2740             :   printTypeTestResolution(TIS.TTRes);
    2741           1 :   if (!TIS.WPDRes.empty()) {
    2742             :     Out << ", wpdResolutions: (";
    2743           1 :     FieldSeparator FS;
    2744             :     for (auto &WPDRes : TIS.WPDRes) {
    2745           1 :       Out << FS;
    2746             :       Out << "(offset: " << WPDRes.first << ", ";
    2747             :       printWPDRes(WPDRes.second);
    2748           0 :       Out << ")";
    2749             :     }
    2750             :     Out << ")";
    2751             :   }
    2752           0 :   Out << ")";
    2753             : }
    2754             : 
    2755           0 : void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
    2756             :   Out << "args: (";
    2757           0 :   FieldSeparator FS;
    2758             :   for (auto arg : Args) {
    2759           0 :     Out << FS;
    2760             :     Out << arg;
    2761           0 :   }
    2762             :   Out << ")";
    2763             : }
    2764           0 : 
    2765             : void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
    2766             :   Out << "wpdRes: (kind: ";
    2767           0 :   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
    2768           0 : 
    2769           0 :   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
    2770             :     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
    2771             : 
    2772             :   if (!WPDRes.ResByArg.empty()) {
    2773           0 :     Out << ", resByArg: (";
    2774           0 :     FieldSeparator FS;
    2775           0 :     for (auto &ResByArg : WPDRes.ResByArg) {
    2776           0 :       Out << FS;
    2777           0 :       printArgs(ResByArg.first);
    2778             :       Out << ", byArg: (kind: ";
    2779           0 :       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
    2780           0 :       if (ResByArg.second.TheKind ==
    2781           0 :               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
    2782             :           ResByArg.second.TheKind ==
    2783           0 :               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
    2784           0 :         Out << ", info: " << ResByArg.second.Info;
    2785             : 
    2786          16 :       // The following fields are only used if the target does not support the
    2787          16 :       // use of absolute symbols to store constants. Print only if non-zero.
    2788          16 :       if (ResByArg.second.Byte || ResByArg.second.Bit)
    2789          16 :         Out << ", byte: " << ResByArg.second.Byte
    2790           4 :             << ", bit: " << ResByArg.second.Bit;
    2791             : 
    2792          13 :       Out << ")";
    2793           9 :     }
    2794           9 :     Out << ")";
    2795           9 :   }
    2796           9 :   Out << ")";
    2797             : }
    2798           4 : 
    2799             : static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
    2800          16 :   switch (SK) {
    2801          16 :   case GlobalValueSummary::AliasKind:
    2802             :     return "alias";
    2803           0 :   case GlobalValueSummary::FunctionKind:
    2804           0 :     return "function";
    2805             :   case GlobalValueSummary::GlobalVarKind:
    2806           0 :     return "variable";
    2807           0 :   }
    2808           0 :   llvm_unreachable("invalid summary kind");
    2809             : }
    2810           0 : 
    2811           0 : void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
    2812             :   Out << ", aliasee: ";
    2813           9 :   // The indexes emitted for distributed backends may not include the
    2814           9 :   // aliasee summary (only if it is being imported directly). Handle
    2815          17 :   // that case by just emitting "null" as the aliasee.
    2816             :   if (AS->hasAliasee())
    2817           9 :     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
    2818           8 :   else
    2819             :     Out << "null";
    2820           9 : }
    2821           1 : 
    2822             : void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
    2823           5 :   // Nothing for now
    2824           4 : }
    2825           4 : 
    2826           4 : static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
    2827           7 :   switch (LT) {
    2828           8 :   case GlobalValue::ExternalLinkage:
    2829           4 :     return "external";
    2830             :   case GlobalValue::PrivateLinkage:
    2831             :     return "private";
    2832           2 :   case GlobalValue::InternalLinkage:
    2833             :     return "internal";
    2834             :   case GlobalValue::LinkOnceAnyLinkage:
    2835             :     return "linkonce";
    2836           4 :   case GlobalValue::LinkOnceODRLinkage:
    2837           1 :     return "linkonce_odr";
    2838           1 :   case GlobalValue::WeakAnyLinkage:
    2839             :     return "weak";
    2840           4 :   case GlobalValue::WeakODRLinkage:
    2841             :     return "weak_odr";
    2842           1 :   case GlobalValue::CommonLinkage:
    2843             :     return "common";
    2844           9 :   case GlobalValue::AppendingLinkage:
    2845           9 :     return "appending";
    2846             :   case GlobalValue::ExternalWeakLinkage:
    2847             :     return "extern_weak";
    2848         224 :   case GlobalValue::AvailableExternallyLinkage:
    2849             :     return "available_externally";
    2850             :   }
    2851         177 :   llvm_unreachable("invalid linkage");
    2852             : }
    2853          34 : 
    2854             : // When printing the linkage types in IR where the ExternalLinkage is
    2855             : // not printed, and other linkage types are expected to be printed with
    2856           0 : // a space after the name.
    2857             : static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
    2858             :   if (LT == GlobalValue::ExternalLinkage)
    2859          13 :     return "";
    2860          13 :   return getLinkageName(LT) + " ";
    2861             : }
    2862             : 
    2863             : void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
    2864          13 :   Out << ", insts: " << FS->instCount();
    2865          22 : 
    2866             :   FunctionSummary::FFlags FFlags = FS->fflags();
    2867           2 :   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
    2868          13 :       FFlags.ReturnDoesNotAlias) {
    2869             :     Out << ", funcFlags: (";
    2870           0 :     Out << "readNone: " << FFlags.ReadNone;
    2871             :     Out << ", readOnly: " << FFlags.ReadOnly;
    2872           0 :     Out << ", noRecurse: " << FFlags.NoRecurse;
    2873             :     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
    2874      111017 :     Out << ")";
    2875      111017 :   }
    2876             :   if (!FS->calls().empty()) {
    2877         178 :     Out << ", calls: (";
    2878             :     FieldSeparator IFS;
    2879       25147 :     for (auto &Call : FS->calls()) {
    2880             :       Out << IFS;
    2881       33538 :       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
    2882             :       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
    2883        1039 :         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
    2884             :       else if (Call.second.RelBlockFreq)
    2885       27276 :         Out << ", relbf: " << Call.second.RelBlockFreq;
    2886             :       Out << ")";
    2887       10424 :     }
    2888             :     Out << ")";
    2889        2802 :   }
    2890             : 
    2891        4361 :   if (const auto *TIdInfo = FS->getTypeIdInfo())
    2892             :     printTypeIdInfo(*TIdInfo);
    2893        3116 : }
    2894             : 
    2895        2446 : void AssemblyWriter::printTypeIdInfo(
    2896             :     const FunctionSummary::TypeIdInfo &TIDInfo) {
    2897         690 :   Out << ", typeIdInfo: (";
    2898             :   FieldSeparator TIDFS;
    2899           0 :   if (!TIDInfo.TypeTests.empty()) {
    2900             :     Out << TIDFS;
    2901             :     Out << "typeTests: (";
    2902             :     FieldSeparator FS;
    2903             :     for (auto &GUID : TIDInfo.TypeTests) {
    2904             :       auto TidIter = TheIndex->typeIds().equal_range(GUID);
    2905      295735 :       if (TidIter.first == TidIter.second) {
    2906      295735 :         Out << FS;
    2907      184942 :         Out << GUID;
    2908      221586 :         continue;
    2909             :       }
    2910             :       // Print all type id that correspond to this GUID.
    2911         177 :       for (auto It = TidIter.first; It != TidIter.second; ++It) {
    2912         177 :         Out << FS;
    2913             :         auto Slot = Machine.getTypeIdSlot(It->second.first);
    2914         177 :         assert(Slot != -1);
    2915         177 :         Out << "^" << Slot;
    2916             :       }
    2917           2 :     }
    2918           2 :     Out << ")";
    2919           2 :   }
    2920           2 :   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
    2921           2 :     Out << TIDFS;
    2922           2 :     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
    2923             :   }
    2924         177 :   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
    2925          39 :     Out << TIDFS;
    2926             :     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
    2927         121 :   }
    2928          82 :   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
    2929          82 :     Out << TIDFS;
    2930          82 :     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
    2931          84 :                      "typeTestAssumeConstVCalls");
    2932          40 :   }
    2933           3 :   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
    2934          82 :     Out << TIDFS;
    2935             :     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
    2936          39 :                      "typeCheckedLoadConstVCalls");
    2937             :   }
    2938             :   Out << ")";
    2939         177 : }
    2940          69 : 
    2941         177 : void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
    2942             :   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
    2943          69 :   if (TidIter.first == TidIter.second) {
    2944             :     Out << "vFuncId: (";
    2945          69 :     Out << "guid: " << VFId.GUID;
    2946             :     Out << ", offset: " << VFId.Offset;
    2947          69 :     Out << ")";
    2948          35 :     return;
    2949          35 :   }
    2950             :   // Print all type id that correspond to this GUID.
    2951          77 :   FieldSeparator FS;
    2952          42 :   for (auto It = TidIter.first; It != TidIter.second; ++It) {
    2953          42 :     Out << FS;
    2954          30 :     Out << "vFuncId: (";
    2955          30 :     auto Slot = Machine.getTypeIdSlot(It->second.first);
    2956             :     assert(Slot != -1);
    2957             :     Out << "^" << Slot;
    2958             :     Out << ", offset: " << VFId.Offset;
    2959          24 :     Out << ")";
    2960          12 :   }
    2961          24 : }
    2962             : 
    2963          12 : void AssemblyWriter::printNonConstVCalls(
    2964             :     const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
    2965             :   Out << Tag << ": (";
    2966          35 :   FieldSeparator FS;
    2967             :   for (auto &VFuncId : VCallList) {
    2968          69 :     Out << FS;
    2969          13 :     printVFuncId(VFuncId);
    2970          26 :   }
    2971             :   Out << ")";
    2972          69 : }
    2973          10 : 
    2974          20 : void AssemblyWriter::printConstVCalls(
    2975             :     const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
    2976          69 :   Out << Tag << ": (";
    2977           7 :   FieldSeparator FS;
    2978           7 :   for (auto &ConstVCall : VCallList) {
    2979             :     Out << FS;
    2980             :     Out << "(";
    2981          69 :     printVFuncId(ConstVCall.VFunc);
    2982           7 :     if (!ConstVCall.Args.empty()) {
    2983           7 :       Out << ", ";
    2984             :       printArgs(ConstVCall.Args);
    2985             :     }
    2986          69 :     Out << ")";
    2987          69 :   }
    2988             :   Out << ")";
    2989          53 : }
    2990          53 : 
    2991          53 : void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
    2992          42 :   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
    2993          42 :   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
    2994          42 :   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
    2995          42 :   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
    2996             :       << ", flags: (";
    2997             :   Out << "linkage: " << getLinkageName(LT);
    2998             :   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
    2999             :   Out << ", live: " << GVFlags.Live;
    3000          22 :   Out << ", dsoLocal: " << GVFlags.DSOLocal;
    3001          11 :   Out << ")";
    3002          11 : 
    3003          22 :   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
    3004             :     printAliasSummary(cast<AliasSummary>(&Summary));
    3005          11 :   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
    3006          11 :     printFunctionSummary(cast<FunctionSummary>(&Summary));
    3007          11 :   else
    3008             :     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
    3009             : 
    3010             :   auto RefList = Summary.refs();
    3011          23 :   if (!RefList.empty()) {
    3012             :     Out << ", refs: (";
    3013          23 :     FieldSeparator FS;
    3014             :     for (auto &Ref : RefList) {
    3015          55 :       Out << FS;
    3016          32 :       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
    3017          32 :     }
    3018             :     Out << ")";
    3019          23 :   }
    3020          23 : 
    3021             :   Out << ")";
    3022          14 : }
    3023             : 
    3024          14 : void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
    3025             :   Out << "^" << Slot << " = gv: (";
    3026          35 :   if (!VI.name().empty())
    3027          21 :     Out << "name: \"" << VI.name() << "\"";
    3028          21 :   else
    3029          21 :     Out << "guid: " << VI.getGUID();
    3030          21 :   if (!VI.getSummaryList().empty()) {
    3031          20 :     Out << ", summaries: (";
    3032          20 :     FieldSeparator FS;
    3033             :     for (auto &Summary : VI.getSummaryList()) {
    3034          21 :       Out << FS;
    3035             :       printSummary(*Summary);
    3036          14 :     }
    3037          14 :     Out << ")";
    3038             :   }
    3039         224 :   Out << ")";
    3040         224 :   if (!VI.name().empty())
    3041         224 :     Out << " ; guid = " << VI.getGUID();
    3042         435 :   Out << "\n";
    3043         224 : }
    3044         224 : 
    3045         224 : static void printMetadataIdentifier(StringRef Name,
    3046         224 :                                     formatted_raw_ostream &Out) {
    3047         224 :   if (Name.empty()) {
    3048         224 :     Out << "<empty name> ";
    3049         224 :   } else {
    3050             :     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
    3051         224 :         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
    3052          13 :       Out << Name[0];
    3053         211 :     else
    3054         177 :       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
    3055             :     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
    3056             :       unsigned char C = Name[i];
    3057             :       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
    3058             :           C == '.' || C == '_')
    3059         224 :         Out << C;
    3060          36 :       else
    3061             :         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
    3062          87 :     }
    3063          51 :   }
    3064          51 : }
    3065             : 
    3066          36 : void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
    3067             :   Out << '!';
    3068             :   printMetadataIdentifier(NMD->getName(), Out);
    3069         224 :   Out << " = !{";
    3070         224 :   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
    3071             :     if (i)
    3072         318 :       Out << ", ";
    3073         636 : 
    3074         318 :     // Write DIExpressions inline.
    3075         212 :     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
    3076             :     MDNode *Op = NMD->getOperand(i);
    3077         106 :     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
    3078         318 :       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
    3079         224 :       continue;
    3080             :     }
    3081         448 : 
    3082         224 :     int Slot = Machine.getMetadataSlot(Op);
    3083         224 :     if (Slot == -1)
    3084             :       Out << "<badref>";
    3085         224 :     else
    3086             :       Out << '!' << Slot;
    3087         318 :   }
    3088         318 :   Out << "}\n";
    3089         212 : }
    3090         318 : 
    3091         318 : static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
    3092             :                             formatted_raw_ostream &Out) {
    3093      163982 :   switch (Vis) {
    3094             :   case GlobalValue::DefaultVisibility: break;
    3095      163982 :   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
    3096           1 :   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
    3097             :   }
    3098          28 : }
    3099      164009 : 
    3100      163955 : static void PrintDSOLocation(const GlobalValue &GV,
    3101             :                              formatted_raw_ostream &Out) {
    3102          78 :   // GVs with local linkage or non default visibility are implicitly dso_local,
    3103     1790303 :   // so we don't print it.
    3104     1626322 :   bool Implicit = GV.hasLocalLinkage() ||
    3105     1626322 :                   (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
    3106      172677 :   if (GV.isDSOLocal() && !Implicit)
    3107     1626317 :     Out << "dso_local ";
    3108             : }
    3109          10 : 
    3110             : static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
    3111             :                                  formatted_raw_ostream &Out) {
    3112      163982 :   switch (SCT) {
    3113             :   case GlobalValue::DefaultStorageClass: break;
    3114           0 :   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
    3115           0 :   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
    3116           0 :   }
    3117           0 : }
    3118           0 : 
    3119           0 : static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
    3120           0 :                                   formatted_raw_ostream &Out) {
    3121             :   switch (TLM) {
    3122             :     case GlobalVariable::NotThreadLocal:
    3123             :       break;
    3124           0 :     case GlobalVariable::GeneralDynamicTLSModel:
    3125           0 :       Out << "thread_local ";
    3126           0 :       break;
    3127           0 :     case GlobalVariable::LocalDynamicTLSModel:
    3128             :       Out << "thread_local(localdynamic) ";
    3129             :       break;
    3130           0 :     case GlobalVariable::InitialExecTLSModel:
    3131           0 :       Out << "thread_local(initialexec) ";
    3132           0 :       break;
    3133             :     case GlobalVariable::LocalExecTLSModel:
    3134           0 :       Out << "thread_local(localexec) ";
    3135             :       break;
    3136           0 :   }
    3137           0 : }
    3138             : 
    3139      295735 : static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
    3140             :   switch (UA) {
    3141      295735 :   case GlobalVariable::UnnamedAddr::None:
    3142             :     return "";
    3143        5844 :   case GlobalVariable::UnnamedAddr::Local:
    3144          73 :     return "local_unnamed_addr";
    3145             :   case GlobalVariable::UnnamedAddr::Global:
    3146      295735 :     return "unnamed_addr";
    3147             :   }
    3148      295735 :   llvm_unreachable("Unknown UnnamedAddr");
    3149             : }
    3150             : 
    3151             : static void maybePrintComdat(formatted_raw_ostream &Out,
    3152      237060 :                              const GlobalObject &GO) {
    3153      234614 :   const Comdat *C = GO.getComdat();
    3154      295735 :   if (!C)
    3155       15965 :     return;
    3156      295735 : 
    3157             :   if (isa<GlobalVariable>(GO))
    3158      295735 :     Out << ',';
    3159             :   Out << " comdat";
    3160      295735 : 
    3161             :   if (GO.getName() == C->getName())
    3162        1804 :     return;
    3163        2751 : 
    3164             :   Out << '(';
    3165      295735 :   PrintLLVMName(Out, C->getName(), ComdatPrefix);
    3166             :   Out << ')';
    3167       86197 : }
    3168             : 
    3169       86197 : void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
    3170             :   if (GV->isMaterializable())
    3171             :     Out << "; Materializable\n";
    3172         365 : 
    3173         365 :   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
    3174         365 :   Out << " = ";
    3175          33 : 
    3176          33 :   if (!GV->hasInitializer() && GV->hasExternalLinkage())
    3177          33 :     Out << "external ";
    3178         892 : 
    3179         892 :   Out << getLinkageNameWithSpace(GV->getLinkage());
    3180         892 :   PrintDSOLocation(*GV, Out);
    3181          32 :   PrintVisibility(GV->getVisibility(), Out);
    3182          32 :   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
    3183          32 :   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
    3184             :   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
    3185       86197 :   if (!UA.empty())
    3186             :       Out << UA << ' ';
    3187             : 
    3188      295735 :   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
    3189             :     Out << "addrspace(" << AddressSpace << ") ";
    3190             :   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
    3191             :   Out << (GV->isConstant() ? "constant " : "global ");
    3192             :   TypePrinter.print(GV->getValueType(), Out);
    3193             : 
    3194             :   if (GV->hasInitializer()) {
    3195             :     Out << ' ';
    3196           0 :     writeOperand(GV->getInitializer(), false);
    3197             :   }
    3198             : 
    3199      294460 :   if (GV->hasSection()) {
    3200             :     Out << ", section \"";
    3201      294460 :     printEscapedString(GV->getSection(), Out);
    3202      294460 :     Out << '"';
    3203             :   }
    3204             :   maybePrintComdat(Out, *GV);
    3205       28710 :   if (GV->getAlignment())
    3206        7634 :     Out << ", align " << GV->getAlignment();
    3207       28710 : 
    3208             :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    3209       28710 :   GV->getAllMetadata(MDs);
    3210             :   printMetadataAttachments(MDs, ", ");
    3211             : 
    3212             :   auto Attrs = GV->getAttributes();
    3213        3487 :   if (Attrs.hasAttributes())
    3214             :     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
    3215             : 
    3216             :   printInfoComment(*GV);
    3217       84922 : }
    3218       84922 : 
    3219           0 : void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
    3220             :   if (GIS->isMaterializable())
    3221       84922 :     Out << "; Materializable\n";
    3222       84922 : 
    3223             :   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
    3224       84922 :   Out << " = ";
    3225        9011 : 
    3226             :   Out << getLinkageNameWithSpace(GIS->getLinkage());
    3227      169844 :   PrintDSOLocation(*GIS, Out);
    3228       84922 :   PrintVisibility(GIS->getVisibility(), Out);
    3229      169844 :   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
    3230      169844 :   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
    3231      169844 :   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
    3232       84922 :   if (!UA.empty())
    3233       84922 :       Out << UA << ' ';
    3234       29757 : 
    3235             :   if (isa<GlobalAlias>(GIS))
    3236       84922 :     Out << "alias ";
    3237        2134 :   else if (isa<GlobalIFunc>(GIS))
    3238       84922 :     Out << "ifunc ";
    3239      208605 :   else
    3240       84922 :     llvm_unreachable("Not an alias or ifunc!");
    3241             : 
    3242       84922 :   TypePrinter.print(GIS->getValueType(), Out);
    3243       73918 : 
    3244       73918 :   Out << ", ";
    3245             : 
    3246             :   const Constant *IS = GIS->getIndirectSymbol();
    3247       84922 : 
    3248       14894 :   if (!IS) {
    3249       29788 :     TypePrinter.print(GIS->getType(), Out);
    3250       14894 :     Out << " <<NULL ALIASEE>>";
    3251             :   } else {
    3252       84922 :     writeOperand(IS, !isa<ConstantExpr>(IS));
    3253       84922 :   }
    3254       50914 : 
    3255             :   printInfoComment(*GIS);
    3256             :   Out << '\n';
    3257       84922 : }
    3258       84922 : 
    3259             : void AssemblyWriter::printComdat(const Comdat *C) {
    3260             :   C->print(Out);
    3261       84922 : }
    3262          33 : 
    3263             : void AssemblyWriter::printTypeIdentities() {
    3264       84922 :   if (TypePrinter.empty())
    3265       84922 :     return;
    3266             : 
    3267        1275 :   Out << '\n';
    3268        1275 : 
    3269           0 :   // Emit all numbered types.
    3270             :   auto &NumberedTypes = TypePrinter.getNumberedTypes();
    3271        1275 :   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
    3272        1275 :     Out << '%' << I << " = type ";
    3273             : 
    3274        2550 :     // Make sure we print out at least one level of the type structure, so
    3275        1275 :     // that we do not get %2 = type %2
    3276        2550 :     TypePrinter.printStructBody(NumberedTypes[I], Out);
    3277        2550 :     Out << '\n';
    3278        2550 :   }
    3279        1275 : 
    3280        1275 :   auto &NamedTypes = TypePrinter.getNamedTypes();
    3281         274 :   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
    3282             :     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
    3283        1275 :     Out << " = type ";
    3284        1194 : 
    3285          81 :     // Make sure we print out at least one level of the type structure, so
    3286          81 :     // that we do not get %FILE = type %FILE
    3287             :     TypePrinter.printStructBody(NamedTypes[I], Out);
    3288           0 :     Out << '\n';
    3289             :   }
    3290        1275 : }
    3291             : 
    3292        1275 : /// printFunction - Print all aspects of a function.
    3293             : void AssemblyWriter::printFunction(const Function *F) {
    3294             :   // Print out the return type and name.
    3295             :   Out << '\n';
    3296             : 
    3297           0 :   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
    3298           0 : 
    3299             :   if (F->isMaterializable())
    3300        1275 :     Out << "; Materializable\n";
    3301             : 
    3302             :   const AttributeList &Attrs = F->getAttributes();
    3303        1275 :   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
    3304        1275 :     AttributeSet AS = Attrs.getFnAttributes();
    3305        1275 :     std::string AttrStr;
    3306             : 
    3307           0 :     for (const Attribute &Attr : AS) {
    3308       25549 :       if (!Attr.isStringAttribute()) {
    3309           0 :         if (!AttrStr.empty()) AttrStr += ' ';
    3310             :         AttrStr += Attr.getAsString();
    3311       17389 :       }
    3312       17389 :     }
    3313             : 
    3314             :     if (!AttrStr.empty())
    3315        6173 :       Out << "; Function Attrs: " << AttrStr << '\n';
    3316             :   }
    3317             : 
    3318        6173 :   Machine.incorporateFunction(F);
    3319       13338 : 
    3320        1984 :   if (F->isDeclaration()) {
    3321             :     Out << "declare";
    3322             :     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    3323             :     F->getAllMetadata(MDs);
    3324        1984 :     printMetadataAttachments(MDs, " ");
    3325         992 :     Out << ' ';
    3326             :   } else
    3327             :     Out << "define ";
    3328             : 
    3329       37493 :   Out << getLinkageNameWithSpace(F->getLinkage());
    3330       31320 :   PrintDSOLocation(*F, Out);
    3331       31320 :   PrintVisibility(F->getVisibility(), Out);
    3332             :   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
    3333             : 
    3334             :   // Print the calling convention.
    3335       62640 :   if (F->getCallingConv() != CallingConv::C) {
    3336       31320 :     PrintCallingConv(F->getCallingConv(), Out);
    3337             :     Out << " ";
    3338             :   }
    3339             : 
    3340             :   FunctionType *FT = F->getFunctionType();
    3341      209538 :   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
    3342             :     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
    3343      209538 :   TypePrinter.print(F->getReturnType(), Out);
    3344             :   Out << ' ';
    3345      209538 :   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
    3346             :   Out << '(';
    3347      209538 : 
    3348           6 :   // Loop over the arguments, printing them...
    3349             :   if (F->isDeclaration() && !IsForDebug) {
    3350      209538 :     // We're only interested in the type here - don't print argument names.
    3351      209538 :     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
    3352      146516 :       // Insert commas as we go... the first arg doesn't get a comma
    3353             :       if (I)
    3354             :         Out << ", ";
    3355     1871795 :       // Output type...
    3356     1725279 :       TypePrinter.print(FT->getParamType(I), Out);
    3357      342050 : 
    3358      684100 :       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
    3359             :       if (ArgAttrs.hasAttributes())
    3360             :         Out << ' ' << ArgAttrs.getAsString();
    3361             :     }
    3362      146516 :   } else {
    3363      136083 :     // The arguments are meaningful here, print them in detail.
    3364             :     for (const Argument &Arg : F->args()) {
    3365             :       // Insert commas as we go... the first arg doesn't get a comma
    3366      209538 :       if (Arg.getArgNo() != 0)
    3367             :         Out << ", ";
    3368      209538 :       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
    3369       71934 :     }
    3370             :   }
    3371       71934 : 
    3372       71934 :   // Finish printing arguments...
    3373       71934 :   if (FT->isVarArg()) {
    3374             :     if (FT->getNumParams()) Out << ", ";
    3375      137604 :     Out << "...";  // Output varargs portion of signature!
    3376             :   }
    3377      419076 :   Out << ')';
    3378      209538 :   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
    3379      419076 :   if (!UA.empty())
    3380      419076 :     Out << ' ' << UA;
    3381             :   // We print the function address space if it is non-zero or if we are writing
    3382             :   // a module with a non-zero program address space or if there is no valid
    3383      209538 :   // Module* so that the file can be parsed without the datalayout string.
    3384        8784 :   const Module *Mod = F->getParent();
    3385        8784 :   if (F->getAddressSpace() != 0 || !Mod ||
    3386             :       Mod->getDataLayout().getProgramAddressSpace() != 0)
    3387             :     Out << " addrspace(" << F->getAddressSpace() << ")";
    3388             :   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
    3389      209538 :     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
    3390       12672 :   if (F->hasSection()) {
    3391      419076 :     Out << " section \"";
    3392      209538 :     printEscapedString(F->getSection(), Out);
    3393      209538 :     Out << '"';
    3394      209538 :   }
    3395             :   maybePrintComdat(Out, *F);
    3396             :   if (F->getAlignment())
    3397      209538 :     Out << " align " << F->getAlignment();
    3398             :   if (F->hasGC())
    3399      213095 :     Out << " gc \"" << F->getGC() << '"';
    3400             :   if (F->hasPrefixData()) {
    3401      141161 :     Out << " prefix ";
    3402       79373 :     writeOperand(F->getPrefixData(), true);
    3403             :   }
    3404      282322 :   if (F->hasPrologueData()) {
    3405             :     Out << " prologue ";
    3406      141161 :     writeOperand(F->getPrologueData(), true);
    3407      141161 :   }
    3408       26016 :   if (F->hasPersonalityFn()) {
    3409             :     Out << " personality ";
    3410             :     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
    3411             :   }
    3412      327595 : 
    3413             :   if (F->isDeclaration()) {
    3414      189991 :     Out << '\n';
    3415       87508 :   } else {
    3416      189991 :     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    3417             :     F->getAllMetadata(MDs);
    3418             :     printMetadataAttachments(MDs, " ");
    3419             : 
    3420             :     Out << " {";
    3421      209538 :     // Output all of the function's basic blocks.
    3422        4839 :     for (const BasicBlock &BB : *F)
    3423        4839 :       printBasicBlock(&BB);
    3424             : 
    3425      209538 :     // Output the function's use-lists.
    3426      209538 :     printUseLists(F);
    3427      209538 : 
    3428       53344 :     Out << "}\n";
    3429             :   }
    3430             : 
    3431             :   Machine.purgeFunction();
    3432      209538 : }
    3433      209538 : 
    3434      209497 : /// printArgument - This member is called for every argument that is passed into
    3435         154 : /// the function.  Simply print it out
    3436      209538 : void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
    3437      146516 :   // Output type...
    3438      209538 :   TypePrinter.print(Arg->getType(), Out);
    3439        1372 : 
    3440        2744 :   // Output parameter attributes list
    3441        1372 :   if (Attrs.hasAttributes())
    3442             :     Out << ' ' << Attrs.getAsString();
    3443      209538 : 
    3444      209538 :   // Output name, if available...
    3445       23371 :   if (Arg->hasName()) {
    3446      209538 :     Out << ' ';
    3447         414 :     PrintLLVMName(Out, Arg);
    3448      209538 :   }
    3449          30 : }
    3450          30 : 
    3451             : /// printBasicBlock - This member is called for each basic block in a method.
    3452      209538 : void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
    3453         145 :   if (BB->hasName()) {              // Print out the label if it exists...
    3454         145 :     Out << "\n";
    3455             :     PrintLLVMName(Out, BB->getName(), LabelPrefix);
    3456      209538 :     Out << ':';
    3457        1712 :   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
    3458        1712 :     Out << "\n; <label>:";
    3459             :     int Slot = Machine.getLocalSlot(BB);
    3460             :     if (Slot != -1)
    3461      209538 :       Out << Slot << ":";
    3462       71934 :     else
    3463             :       Out << "<badref>";
    3464             :   }
    3465      137604 : 
    3466      137604 :   if (!BB->getParent()) {
    3467             :     Out.PadToColumn(50);
    3468      137604 :     Out << "; Error: Block without parent!";
    3469             :   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
    3470      449555 :     // Output predecessors for the block.
    3471      311951 :     Out.PadToColumn(50);
    3472             :     Out << ";";
    3473             :     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
    3474      137604 : 
    3475             :     if (PI == PE) {
    3476      137604 :       Out << " No predecessors!";
    3477             :     } else {
    3478             :       Out << " preds = ";
    3479      209538 :       writeOperand(*PI, false);
    3480      209538 :       for (++PI; PI != PE; ++PI) {
    3481             :         Out << ", ";
    3482             :         writeOperand(*PI, false);
    3483             :       }
    3484      189991 :     }
    3485             :   }
    3486      189991 : 
    3487             :   Out << "\n";
    3488             : 
    3489      189991 :   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
    3490      123483 : 
    3491             :   // Output all of the instructions in the basic block...
    3492             :   for (const Instruction &I : *BB) {
    3493      189991 :     printInstructionLine(I);
    3494      179339 :   }
    3495      179339 : 
    3496             :   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
    3497      189991 : }
    3498             : 
    3499             : /// printInstructionLine - Print an instruction and a newline character.
    3500      311992 : void AssemblyWriter::printInstructionLine(const Instruction &I) {
    3501      311992 :   printInstruction(I);
    3502      281748 :   Out << '\n';
    3503      281748 : }
    3504      281748 : 
    3505       30244 : /// printGCRelocateComment - print comment after call to the gc.relocate
    3506        2805 : /// intrinsic indicating base and derived pointer names.
    3507        2805 : void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
    3508        2805 :   Out << " ; (";
    3509        2805 :   writeOperand(Relocate.getBasePtr(), false);
    3510             :   Out << ", ";
    3511           0 :   writeOperand(Relocate.getDerivedPtr(), false);
    3512             :   Out << ")";
    3513             : }
    3514      311992 : 
    3515           0 : /// printInfoComment - Print a little comment after the instruction indicating
    3516           0 : /// which slot it occupies.
    3517      311992 : void AssemblyWriter::printInfoComment(const Value &V) {
    3518             :   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
    3519      174385 :     printGCRelocateComment(*Relocate);
    3520      174385 : 
    3521      174385 :   if (AnnotationWriter)
    3522             :     AnnotationWriter->printInfoComment(V, Out);
    3523      174385 : }
    3524         884 : 
    3525             : static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
    3526      173501 :                                     raw_ostream &Out) {
    3527      173501 :   // We print the address space of the call if it is non-zero.
    3528      235045 :   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
    3529       61544 :   bool PrintAddrSpace = CallAddrSpace != 0;
    3530       61544 :   if (!PrintAddrSpace) {
    3531             :     const Module *Mod = getModuleFromVal(I);
    3532             :     // We also print it if it is zero but not equal to the program address space
    3533             :     // or if we can't find a valid Module* to make it possible to parse
    3534             :     // the resulting file even without a datalayout string.
    3535      311992 :     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
    3536             :       PrintAddrSpace = true;
    3537      311992 :   }
    3538             :   if (PrintAddrSpace)
    3539             :     Out << " addrspace(" << CallAddrSpace << ")";
    3540     2591892 : }
    3541     2279900 : 
    3542             : // This member is called for each Instruction in a function..
    3543             : void AssemblyWriter::printInstruction(const Instruction &I) {
    3544      311992 :   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
    3545      311992 : 
    3546             :   // Print out indentation for an instruction.
    3547             :   Out << "  ";
    3548     2279900 : 
    3549     2279900 :   // Print out name if it exists...
    3550     2279900 :   if (I.hasName()) {
    3551     2279900 :     PrintLLVMName(Out, &I);
    3552             :     Out << " = ";
    3553             :   } else if (!I.getType()->isVoidTy()) {
    3554             :     // Print out the def slot taken.
    3555         485 :     int SlotNum = Machine.getLocalSlot(&I);
    3556         485 :     if (SlotNum == -1)
    3557         485 :       Out << "<badref> = ";
    3558         485 :     else
    3559         485 :       Out << '%' << SlotNum << " = ";
    3560         485 :   }
    3561         485 : 
    3562             :   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
    3563             :     if (CI->isMustTailCall())
    3564             :       Out << "musttail ";
    3565     2401194 :     else if (CI->isTailCall())
    3566             :       Out << "tail ";
    3567         485 :     else if (CI->isNoTailCall())
    3568             :       Out << "notail ";
    3569     2401194 :   }
    3570        1283 : 
    3571     2401194 :   // Print out the opcode...
    3572             :   Out << I.getOpcodeName();
    3573      186508 : 
    3574             :   // If this is an atomic load or store, print out the atomic marker.
    3575             :   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
    3576      186508 :       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
    3577      186508 :     Out << " atomic";
    3578      186508 : 
    3579      186496 :   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
    3580             :     Out << " weak";
    3581             : 
    3582             :   // If this is a volatile operation, print out the volatile marker.
    3583      186496 :   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
    3584             :       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
    3585             :       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
    3586      186481 :       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
    3587          78 :     Out << " volatile";
    3588      186508 : 
    3589             :   // Print out optimization information.
    3590             :   WriteOptimizationInfo(Out, &I);
    3591     2314997 : 
    3592     2314997 :   // Print out the compare instruction predicates
    3593             :   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
    3594             :     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
    3595     2314997 : 
    3596             :   // Print out the atomicrmw operation
    3597             :   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
    3598     2314997 :     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
    3599      773257 : 
    3600      773257 :   // Print out the type of the operands...
    3601     3083480 :   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
    3602             : 
    3603      704340 :   // Special case conditional branches to swizzle the condition out to the front
    3604      704340 :   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
    3605          38 :     const BranchInst &BI(cast<BranchInst>(I));
    3606             :     Out << ' ';
    3607     1408604 :     writeOperand(BI.getCondition(), true);
    3608             :     Out << ", ";
    3609             :     writeOperand(BI.getSuccessor(0), true);
    3610             :     Out << ", ";
    3611      183244 :     writeOperand(BI.getSuccessor(1), true);
    3612         176 : 
    3613      183068 :   } else if (isa<SwitchInst>(I)) {
    3614        8255 :     const SwitchInst& SI(cast<SwitchInst>(I));
    3615      174813 :     // Special case switch instruction to get formatting nice and correct.
    3616          54 :     Out << ' ';
    3617             :     writeOperand(SI.getCondition(), true);
    3618             :     Out << ", ";
    3619             :     writeOperand(SI.getDefaultDest(), true);
    3620     2314997 :     Out << " [";
    3621             :     for (auto Case : SI.cases()) {
    3622             :       Out << "\n    ";
    3623     2314997 :       writeOperand(Case.getCaseValue(), true);
    3624      407837 :       Out << ", ";
    3625        1799 :       writeOperand(Case.getCaseSuccessor(), true);
    3626             :     }
    3627     2314997 :     Out << "\n  ]";
    3628          69 :   } else if (isa<IndirectBrInst>(I)) {
    3629             :     // Special case indirectbr instruction to get formatting nice and correct.
    3630             :     Out << ' ';
    3631     2314997 :     writeOperand(Operand, true);
    3632     2304482 :     Out << ", [";
    3633     4612790 : 
    3634         982 :     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
    3635       17361 :       if (i != 1)
    3636             :         Out << ", ";
    3637             :       writeOperand(I.getOperand(i), true);
    3638     2314997 :     }
    3639             :     Out << ']';
    3640             :   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
    3641             :     Out << ' ';
    3642      139402 :     TypePrinter.print(I.getType(), Out);
    3643             :     Out << ' ';
    3644             : 
    3645             :     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
    3646        1964 :       if (op) Out << ", ";
    3647             :       Out << "[ ";
    3648             :       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
    3649     2314997 :       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
    3650             :     }
    3651             :   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
    3652     2314997 :     Out << ' ';
    3653             :     writeOperand(I.getOperand(0), true);
    3654       59534 :     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
    3655       59534 :       Out << ", " << *i;
    3656       59534 :   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
    3657       59534 :     Out << ' ';
    3658       59534 :     writeOperand(I.getOperand(0), true); Out << ", ";
    3659       59534 :     writeOperand(I.getOperand(1), true);
    3660             :     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
    3661     2255463 :       Out << ", " << *i;
    3662             :   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
    3663             :     Out << ' ';
    3664        1156 :     TypePrinter.print(I.getType(), Out);
    3665        1156 :     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
    3666        1156 :       Out << '\n';
    3667        1156 : 
    3668        1156 :     if (LPI->isCleanup())
    3669        3977 :       Out << "          cleanup";
    3670        2821 : 
    3671        5642 :     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
    3672        2821 :       if (i != 0 || LPI->isCleanup()) Out << "\n";
    3673        2821 :       if (LPI->isCatch(i))
    3674             :         Out << "          catch ";
    3675        1156 :       else
    3676     2254307 :         Out << "          filter ";
    3677             : 
    3678         231 :       writeOperand(LPI->getClause(i), true);
    3679         231 :     }
    3680         231 :   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
    3681             :     Out << " within ";
    3682         845 :     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
    3683         614 :     Out << " [";
    3684         387 :     unsigned Op = 0;
    3685         614 :     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
    3686             :       if (Op > 0)
    3687         231 :         Out << ", ";
    3688             :       writeOperand(PadBB, /*PrintType=*/true);
    3689       28219 :       ++Op;
    3690       28219 :     }
    3691       28219 :     Out << "] unwind ";
    3692             :     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
    3693       84296 :       writeOperand(UnwindDest, /*PrintType=*/true);
    3694       56077 :     else
    3695       56077 :       Out << "to caller";
    3696       56077 :   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
    3697       56077 :     Out << " within ";
    3698             :     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
    3699             :     Out << " [";
    3700        9465 :     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
    3701        9465 :          ++Op) {
    3702       18985 :       if (Op > 0)
    3703        9520 :         Out << ", ";
    3704             :       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
    3705        2580 :     }
    3706        2580 :     Out << ']';
    3707        2580 :   } else if (isa<ReturnInst>(I) && !Operand) {
    3708        5202 :     Out << " void";
    3709        2622 :   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
    3710             :     Out << " from ";
    3711        1857 :     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
    3712        1857 : 
    3713        1857 :     Out << " to ";
    3714        1857 :     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
    3715             :   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
    3716        1857 :     Out << " from ";
    3717         923 :     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
    3718             : 
    3719        2919 :     Out << " unwind ";
    3720        1062 :     if (CRI->hasUnwindDest())
    3721        1062 :       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
    3722        1001 :     else
    3723             :       Out << "to caller";
    3724          61 :   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
    3725             :     // Print the calling convention being used.
    3726        1062 :     if (CI->getCallingConv() != CallingConv::C) {
    3727             :       Out << " ";
    3728             :       PrintCallingConv(CI->getCallingConv(), Out);
    3729         306 :     }
    3730         306 : 
    3731         306 :     Operand = CI->getCalledValue();
    3732             :     FunctionType *FTy = CI->getFunctionType();
    3733         625 :     Type *RetTy = FTy->getReturnType();
    3734         319 :     const AttributeList &PAL = CI->getAttributes();
    3735          13 : 
    3736         319 :     if (PAL.hasAttributes(AttributeList::ReturnIndex))
    3737         319 :       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
    3738             : 
    3739         306 :     // Only print addrspace(N) if necessary:
    3740             :     maybePrintCallAddrSpace(Operand, &I, Out);
    3741          84 : 
    3742             :     // If possible, print out the short form of the call instruction.  We can
    3743         222 :     // only do this if the first argument is a pointer to a nonvararg function,
    3744             :     // and if the return type is not a pointer to a function.
    3745         770 :     //
    3746         770 :     Out << ' ';
    3747         770 :     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
    3748        1225 :     Out << ' ';
    3749             :     writeOperand(Operand, false);
    3750         455 :     Out << '(';
    3751         223 :     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
    3752         455 :       if (op > 0)
    3753             :         Out << ", ";
    3754         770 :       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
    3755     2210879 :     }
    3756       75831 : 
    3757             :     // Emit an ellipsis if this is a musttail call in a vararg function.  This
    3758         233 :     // is only to aid readability, musttail calls forward varargs by default.
    3759         233 :     if (CI->isMustTailCall() && CI->getParent() &&
    3760             :         CI->getParent()->getParent() &&
    3761         233 :         CI->getParent()->getParent()->isVarArg())
    3762         233 :       Out << ", ...";
    3763             : 
    3764         330 :     Out << ')';
    3765         330 :     if (PAL.hasAttributes(AttributeList::FunctionIndex))
    3766             :       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
    3767         330 : 
    3768         330 :     writeOperandBundles(CI);
    3769         118 :   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
    3770             :     Operand = II->getCalledValue();
    3771         212 :     FunctionType *FTy = II->getFunctionType();
    3772             :     Type *RetTy = FTy->getReturnType();
    3773             :     const AttributeList &PAL = II->getAttributes();
    3774      183244 : 
    3775        5169 :     // Print the calling convention being used.
    3776       10338 :     if (II->getCallingConv() != CallingConv::C) {
    3777             :       Out << " ";
    3778             :       PrintCallingConv(II->getCallingConv(), Out);
    3779             :     }
    3780      183244 : 
    3781      183244 :     if (PAL.hasAttributes(AttributeList::ReturnIndex))
    3782      183244 :       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
    3783             : 
    3784      183244 :     // Only print addrspace(N) if necessary:
    3785        7842 :     maybePrintCallAddrSpace(Operand, &I, Out);
    3786             : 
    3787             :     // If possible, print out the short form of the invoke instruction. We can
    3788      183244 :     // only do this if the first argument is a pointer to a nonvararg function,
    3789             :     // and if the return type is not a pointer to a function.
    3790             :     //
    3791             :     Out << ' ';
    3792             :     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
    3793             :     Out << ' ';
    3794      183244 :     writeOperand(Operand, false);
    3795      540334 :     Out << '(';
    3796      183244 :     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
    3797      183244 :       if (op)
    3798      183244 :         Out << ", ";
    3799      769819 :       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
    3800      403331 :     }
    3801      246250 : 
    3802      806662 :     Out << ')';
    3803             :     if (PAL.hasAttributes(AttributeList::FunctionIndex))
    3804             :       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
    3805             : 
    3806             :     writeOperandBundles(II);
    3807         176 : 
    3808      183420 :     Out << "\n          to ";
    3809             :     writeOperand(II->getNormalDest(), true);
    3810          92 :     Out << " unwind ";
    3811             :     writeOperand(II->getUnwindDest(), true);
    3812      183244 :   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
    3813      183244 :     Out << ' ';
    3814       56405 :     if (AI->isUsedWithInAlloca())
    3815             :       Out << "inalloca ";
    3816      183244 :     if (AI->isSwiftError())
    3817             :       Out << "swifterror ";
    3818             :     TypePrinter.print(AI->getAllocatedType(), Out);
    3819        3264 : 
    3820        3264 :     // Explicitly write the array size if the code is broken, if it's an array
    3821        3264 :     // allocation, or if the type is not canonical for scalar allocations.  The
    3822             :     // latter case prevents the type from mutating when round-tripping through
    3823             :     // assembly.
    3824        3264 :     if (!AI->getArraySize() || AI->isArrayAllocation() ||
    3825          43 :         !AI->getArraySize()->getType()->isIntegerTy(32)) {
    3826          86 :       Out << ", ";
    3827             :       writeOperand(AI->getArraySize(), true);
    3828             :     }
    3829        3264 :     if (AI->getAlignment()) {
    3830         861 :       Out << ", align " << AI->getAlignment();
    3831             :     }
    3832             : 
    3833        3264 :     unsigned AddrSpace = AI->getType()->getAddressSpace();
    3834             :     if (AddrSpace != 0) {
    3835             :       Out << ", addrspace(" << AddrSpace << ')';
    3836             :     }
    3837             :   } else if (isa<CastInst>(I)) {
    3838             :     if (Operand) {
    3839        3264 :       Out << ' ';
    3840        9698 :       writeOperand(Operand, true);   // Work with broken code
    3841        3264 :     }
    3842        3264 :     Out << " to ";
    3843        3264 :     TypePrinter.print(I.getType(), Out);
    3844        9573 :   } else if (isa<VAArgInst>(I)) {
    3845        3045 :     if (Operand) {
    3846        1306 :       Out << ' ';
    3847        6090 :       writeOperand(Operand, true);   // Work with broken code
    3848             :     }
    3849             :     Out << ", ";
    3850        3264 :     TypePrinter.print(I.getType(), Out);
    3851        3264 :   } else if (Operand) {   // Print the normal way.
    3852         218 :     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
    3853             :       Out << ' ';
    3854        3264 :       TypePrinter.print(GEP->getSourceElementType(), Out);
    3855             :       Out << ',';
    3856        3264 :     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
    3857        3264 :       Out << ' ';
    3858        3264 :       TypePrinter.print(LI->getType(), Out);
    3859        3264 :       Out << ',';
    3860             :     }
    3861      319768 : 
    3862      319768 :     // PrintAllTypes - Instructions who have operands of all the same type
    3863         118 :     // omit the type from all but the first operand.  If the instruction has
    3864      319768 :     // different type operands (for example br), then they are all printed.
    3865          27 :     bool PrintAllTypes = false;
    3866      319768 :     Type *TheType = Operand->getType();
    3867             : 
    3868             :     // Select, Store and ShuffleVector always print all types.
    3869             :     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
    3870             :         || isa<ReturnInst>(I)) {
    3871             :       PrintAllTypes = true;
    3872      638048 :     } else {
    3873      318280 :       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
    3874        1496 :         Operand = I.getOperand(i);
    3875        1496 :         // note that Operand shouldn't be null, but the test helps make dump()
    3876             :         // more tolerant of malformed IR
    3877      319768 :         if (Operand && Operand->getType() != TheType) {
    3878      316732 :           PrintAllTypes = true;    // We have differing types!  Print them all!
    3879             :           break;
    3880             :         }
    3881             :       }
    3882      319768 :     }
    3883        1210 : 
    3884             :     if (!PrintAllTypes) {
    3885     1628209 :       Out << ' ';
    3886      203403 :       TypePrinter.print(TheType, Out);
    3887      203403 :     }
    3888      203403 : 
    3889             :     Out << ' ';
    3890      203403 :     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
    3891      203403 :       if (i) Out << ", ";
    3892     1424806 :       writeOperand(I.getOperand(i), PrintAllTypes);
    3893          50 :     }
    3894          50 :   }
    3895          50 : 
    3896             :   // Print atomic ordering/alignment for memory operations
    3897          50 :   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
    3898          50 :     if (LI->isAtomic())
    3899     1424756 :       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
    3900             :     if (LI->getAlignment())
    3901      145867 :       Out << ", align " << LI->getAlignment();
    3902      145867 :   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
    3903      145867 :     if (SI->isAtomic())
    3904             :       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
    3905      428938 :     if (SI->getAlignment())
    3906      428938 :       Out << ", align " << SI->getAlignment();
    3907      428938 :   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
    3908             :     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
    3909             :                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
    3910             :   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
    3911             :     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
    3912             :                 RMWI->getSyncScopeID());
    3913             :   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
    3914     1419640 :     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
    3915             :   }
    3916             : 
    3917     1411765 :   // Print Metadata info.
    3918     2411748 :   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
    3919             :   I.getAllMetadata(InstMD);
    3920             :   printMetadataAttachments(InstMD, ", ");
    3921     1142111 : 
    3922             :   // Print a nice comment.
    3923             :   printInfoComment(I);
    3924             : }
    3925      389694 : 
    3926             : void AssemblyWriter::printMetadataAttachments(
    3927             :     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
    3928             :     StringRef Separator) {
    3929             :   if (MDs.empty())
    3930             :     return;
    3931             : 
    3932      923669 :   if (MDNames.empty())
    3933      752417 :     MDs[0].second->getContext().getMDKindNames(MDNames);
    3934      752417 : 
    3935             :   for (const auto &I : MDs) {
    3936             :     unsigned Kind = I.first;
    3937     1419640 :     Out << Separator;
    3938     3788587 :     if (Kind < MDNames.size()) {
    3939     2368947 :       Out << "!";
    3940     4737894 :       printMetadataIdentifier(MDNames[Kind], Out);
    3941             :     } else
    3942             :       Out << "!<unknown kind #" << Kind << ">";
    3943             :     Out << ' ';
    3944             :     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
    3945             :   }
    3946      428938 : }
    3947        2342 : 
    3948      428938 : void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
    3949      420574 :   Out << '!' << Slot << " = ";
    3950             :   printMDNodeBody(Node);
    3951      407837 :   Out << "\n";
    3952        1256 : }
    3953      407837 : 
    3954      397368 : void AssemblyWriter::writeAllMDNodes() {
    3955             :   SmallVector<const MDNode *, 16> Nodes;
    3956         709 :   Nodes.resize(Machine.mdn_size());
    3957         709 :   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
    3958             :        I != E; ++I)
    3959         982 :     Nodes[I->second] = cast<MDNode>(I->first);
    3960         982 : 
    3961             :   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
    3962         512 :     writeMDNode(i, Nodes[i]);
    3963             :   }
    3964             : }
    3965             : 
    3966             : void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
    3967             :   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
    3968     2314997 : }
    3969             : 
    3970             : void AssemblyWriter::writeAllAttributeGroups() {
    3971     2314997 :   std::vector<std::pair<AttributeSet, unsigned>> asVec;
    3972     2314997 :   asVec.resize(Machine.as_size());
    3973             : 
    3974     2609457 :   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
    3975             :        I != E; ++I)
    3976             :     asVec[I->second] = *I;
    3977     2609457 : 
    3978             :   for (const auto &I : asVec)
    3979             :     Out << "attributes #" << I.second << " = { "
    3980      132215 :         << I.first.getAsString(true) << " }\n";
    3981       12704 : }
    3982             : 
    3983      275594 : void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
    3984      143379 :   bool IsInFunction = Machine.getFunction();
    3985      143379 :   if (IsInFunction)
    3986      143379 :     Out << "  ";
    3987      143379 : 
    3988      286758 :   Out << "uselistorder";
    3989             :   if (const BasicBlock *BB =
    3990           0 :           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
    3991      143379 :     Out << "_bb ";
    3992      143379 :     writeOperand(BB->getParent(), false);
    3993             :     Out << ", ";
    3994             :     writeOperand(BB, false);
    3995             :   } else {
    3996      102707 :     Out << " ";
    3997      205414 :     writeOperand(Order.V, true);
    3998             :   }
    3999      102707 :   Out << ", { ";
    4000      102707 : 
    4001             :   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
    4002       10578 :   Out << Order.Shuffle[0];
    4003             :   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
    4004       21156 :     Out << ", " << Order.Shuffle[I];
    4005       10578 :   Out << " }\n";
    4006      113285 : }
    4007      205414 : 
    4008             : void AssemblyWriter::printUseLists(const Function *F) {
    4009      113285 :   auto hasMore =
    4010      205414 :       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
    4011             :   if (!hasMore())
    4012       10578 :     // Nothing to do.
    4013             :     return;
    4014             : 
    4015      102707 :   Out << "\n; uselistorder directives\n";
    4016             :   while (hasMore()) {
    4017             :     printUseListOrder(UseListOrders.back());
    4018           0 :     UseListOrders.pop_back();
    4019             :   }
    4020           0 : }
    4021             : 
    4022           0 : //===----------------------------------------------------------------------===//
    4023           0 : //                       External Interface declarations
    4024           0 : //===----------------------------------------------------------------------===//
    4025             : 
    4026           0 : void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
    4027           0 :                      bool ShouldPreserveUseListOrder,
    4028           0 :                      bool IsForDebug) const {
    4029           0 :   SlotTracker SlotTable(this->getParent());
    4030             :   formatted_raw_ostream OS(ROS);
    4031         855 :   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
    4032         855 :                    IsForDebug,
    4033         855 :                    ShouldPreserveUseListOrder);
    4034         740 :   W.printFunction(this);
    4035             : }
    4036         855 : 
    4037             : void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
    4038         855 :                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
    4039           0 :   SlotTracker SlotTable(this);
    4040           0 :   formatted_raw_ostream OS(ROS);
    4041           0 :   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
    4042           0 :                    ShouldPreserveUseListOrder);
    4043             :   W.printModule(this);
    4044         855 : }
    4045         855 : 
    4046             : void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
    4047         855 :   SlotTracker SlotTable(getParent());
    4048             :   formatted_raw_ostream OS(ROS);
    4049             :   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
    4050         855 :   W.printNamedMDNode(this);
    4051        4034 : }
    4052        2324 : 
    4053         855 : void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
    4054         855 :                         bool IsForDebug) const {
    4055             :   Optional<SlotTracker> LocalST;
    4056      154993 :   SlotTracker *SlotTable;
    4057             :   if (auto *ST = MST.getMachine())
    4058      156235 :     SlotTable = ST;
    4059             :   else {
    4060             :     LocalST.emplace(getParent());
    4061             :     SlotTable = &*LocalST;
    4062             :   }
    4063         387 : 
    4064             :   formatted_raw_ostream OS(ROS);
    4065         855 :   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
    4066             :   W.printNamedMDNode(this);
    4067             : }
    4068             : 
    4069             : void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
    4070             :   PrintLLVMName(ROS, getName(), ComdatPrefix);
    4071             :   ROS << " = comdat ";
    4072             : 
    4073             :   switch (getSelectionKind()) {
    4074         149 :   case Comdat::Any:
    4075             :     ROS << "any";
    4076             :     break;
    4077         298 :   case Comdat::ExactMatch:
    4078         149 :     ROS << "exactmatch";
    4079             :     break;
    4080             :   case Comdat::Largest:
    4081         298 :     ROS << "largest";
    4082         149 :     break;
    4083         149 :   case Comdat::NoDuplicates:
    4084             :     ROS << "noduplicates";
    4085       17389 :     break;
    4086             :   case Comdat::SameSize:
    4087       34777 :     ROS << "samesize";
    4088       17389 :     break;
    4089             :   }
    4090       34778 : 
    4091       17389 :   ROS << '\n';
    4092       17388 : }
    4093             : 
    4094           1 : void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
    4095           2 :   TypePrinting TP;
    4096           1 :   TP.print(const_cast<Type*>(this), OS);
    4097           2 : 
    4098           1 :   if (NoDetails)
    4099           1 :     return;
    4100             : 
    4101           7 :   // If the type is a named struct type, print the body as well.
    4102             :   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
    4103             :     if (!STy->isLiteral()) {
    4104             :       OS << " = type ";
    4105           7 :       TP.printStructBody(STy, OS);
    4106             :     }
    4107             : }
    4108           0 : 
    4109             : static bool isReferencingMDNode(const Instruction &I) {
    4110             :   if (const auto *CI = dyn_cast<CallInst>(&I))
    4111             :     if (Function *F = CI->getCalledFunction())
    4112           7 :       if (F->isIntrinsic())
    4113          14 :         for (auto &Op : I.operands())
    4114           7 :           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
    4115           7 :             if (isa<MDNode>(V->getMetadata()))
    4116             :               return true;
    4117       25549 :   return false;
    4118       25549 : }
    4119       25549 : 
    4120             : void Value::print(raw_ostream &ROS, bool IsForDebug) const {
    4121       25549 :   bool ShouldInitializeAllMetadata = false;
    4122       25311 :   if (auto *I = dyn_cast<Instruction>(this))
    4123       25311 :     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
    4124       25311 :   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
    4125          11 :     ShouldInitializeAllMetadata = true;
    4126          11 : 
    4127          11 :   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
    4128         202 :   print(ROS, MST, IsForDebug);
    4129         202 : }
    4130         202 : 
    4131          16 : void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
    4132          16 :                   bool IsForDebug) const {
    4133          16 :   formatted_raw_ostream OS(ROS);
    4134           9 :   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
    4135           9 :   SlotTracker &SlotTable =
    4136           9 :       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
    4137             :   auto incorporateFunction = [&](const Function *F) {
    4138             :     if (F)
    4139             :       MST.incorporateFunction(*F);
    4140       25549 :   };
    4141             : 
    4142       44882 :   if (const Instruction *I = dyn_cast<Instruction>(this)) {
    4143       44882 :     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
    4144       44882 :     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
    4145             :     W.printInstruction(*I);
    4146       44882 :   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
    4147           0 :     incorporateFunction(BB->getParent());
    4148             :     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
    4149             :     W.printBasicBlock(BB);
    4150             :   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
    4151          86 :     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
    4152          84 :     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
    4153          84 :       W.printGlobal(V);
    4154             :     else if (const Function *F = dyn_cast<Function>(GV))
    4155             :       W.printFunction(F);
    4156             :     else
    4157       34826 :       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
    4158             :   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
    4159             :     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
    4160        3400 :   } else if (const Constant *C = dyn_cast<Constant>(this)) {
    4161        9644 :     TypePrinting TypePrinter;
    4162             :     TypePrinter.print(C->getType(), OS);
    4163           7 :     OS << ' ';
    4164             :     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
    4165             :   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
    4166             :     this->printAsOperand(OS, /* PrintType */ true, MST);
    4167             :   } else {
    4168       35398 :     llvm_unreachable("Unknown value to print out!");
    4169             :   }
    4170             : }
    4171       34826 : 
    4172         572 : /// Print without a type, skipping the TypePrinting object.
    4173             : ///
    4174             : /// \return \c true iff printing was successful.
    4175       70796 : static bool printWithoutType(const Value &V, raw_ostream &O,
    4176       35398 :                              SlotTracker *Machine, const Module *M) {
    4177       35398 :   if (V.hasName() || isa<GlobalValue>(V) ||
    4178             :       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
    4179       35671 :     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
    4180             :     return true;
    4181       35671 :   }
    4182       71342 :   return false;
    4183             : }
    4184       35671 : 
    4185             : static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
    4186       35100 :                                ModuleSlotTracker &MST) {
    4187       35100 :   TypePrinting TypePrinter(MST.getModule());
    4188             :   if (PrintType) {
    4189             :     TypePrinter.print(V.getType(), O);
    4190             :     O << ' ';
    4191       35097 :   }
    4192       70194 : 
    4193       35097 :   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
    4194             :                          MST.getModule());
    4195          41 : }
    4196          82 : 
    4197          41 : void Value::printAsOperand(raw_ostream &O, bool PrintType,
    4198             :                            const Module *M) const {
    4199         496 :   if (!M)
    4200             :     M = getModuleFromVal(this);
    4201          10 : 
    4202             :   if (!PrintType)
    4203         238 :     if (printWithoutType(*this, O, nullptr, M))
    4204             :       return;
    4205           0 : 
    4206             :   SlotTracker Machine(
    4207           4 :       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
    4208             :   ModuleSlotTracker MST(Machine, M);
    4209         101 :   printAsOperandImpl(*this, O, PrintType, MST);
    4210         101 : }
    4211             : 
    4212         101 : void Value::printAsOperand(raw_ostream &O, bool PrintType,
    4213         180 :                            ModuleSlotTracker &MST) const {
    4214         180 :   if (!PrintType)
    4215             :     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
    4216           0 :       return;
    4217             : 
    4218       35671 :   printAsOperandImpl(*this, O, PrintType, MST);
    4219             : }
    4220             : 
    4221             : static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
    4222             :                               ModuleSlotTracker &MST, const Module *M,
    4223      341650 :                               bool OnlyAsOperand) {
    4224             :   formatted_raw_ostream OS(ROS);
    4225      363133 : 
    4226         348 :   TypePrinting TypePrinter(M);
    4227      320511 : 
    4228      320511 :   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
    4229             :                          /* FromValue */ true);
    4230             : 
    4231             :   auto *N = dyn_cast<MDNode>(&MD);
    4232             :   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
    4233       34499 :     return;
    4234             : 
    4235       68998 :   OS << " = ";
    4236       34499 :   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
    4237       13360 : }
    4238             : 
    4239             : void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
    4240             :   ModuleSlotTracker MST(M, isa<MDNode>(this));
    4241       34499 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
    4242             : }
    4243       34499 : 
    4244             : void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
    4245      344447 :                               const Module *M) const {
    4246             :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
    4247      344447 : }
    4248       47989 : 
    4249             : void Metadata::print(raw_ostream &OS, const Module *M,
    4250      344447 :                      bool /*IsForDebug*/) const {
    4251      333191 :   ModuleSlotTracker MST(M, isa<MDNode>(this));
    4252      312054 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
    4253             : }
    4254             : 
    4255       64786 : void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
    4256       64786 :                      const Module *M, bool /*IsForDebug*/) const {
    4257       32393 :   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
    4258             : }
    4259             : 
    4260       10563 : void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
    4261             :   SlotTracker SlotTable(this);
    4262       10563 :   formatted_raw_ostream OS(ROS);
    4263        8459 :   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
    4264             :   W.printModuleSummaryIndex();
    4265             : }
    4266        2106 : 
    4267             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    4268             : // Value::dump - allow easy printing of Values from the debugger.
    4269        8405 : LLVM_DUMP_METHOD
    4270             : void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
    4271             : 
    4272         189 : // Type::dump - allow easy printing of Types from the debugger.
    4273             : LLVM_DUMP_METHOD
    4274         189 : void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
    4275             : 
    4276        8405 : // Module::dump() - Allow printing of Modules from the debugger.
    4277             : LLVM_DUMP_METHOD
    4278             : void Module::dump() const {
    4279             :   print(dbgs(), nullptr,
    4280        8405 :         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
    4281        8216 : }
    4282             : 
    4283         189 : // Allow printing of Comdats from the debugger.
    4284         189 : LLVM_DUMP_METHOD
    4285             : void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
    4286             : 
    4287           2 : // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
    4288           4 : LLVM_DUMP_METHOD
    4289           2 : void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
    4290           2 : 
    4291             : LLVM_DUMP_METHOD
    4292        8178 : void Metadata::dump() const { dump(nullptr); }
    4293             : 
    4294        8178 : LLVM_DUMP_METHOD
    4295        8178 : void Metadata::dump(const Module *M) const {
    4296             :   print(dbgs(), M, /*IsForDebug=*/true);
    4297          14 :   dbgs() << '\n';
    4298             : }
    4299          28 : 
    4300          14 : // Allow printing of ModuleSummaryIndex from the debugger.
    4301          14 : LLVM_DUMP_METHOD
    4302             : void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
    4303         211 : #endif

Generated by: LCOV version 1.13