Path: blob/main/contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp
35233 views
//===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This library implements `print` family of functions in classes like9// Module, Function, Value, etc. In-memory representation of those classes is10// converted to IR strings.11//12// Note that these routines must be extremely tolerant of various errors in the13// LLVM code, because it can be used for debugging transformations.14//15//===----------------------------------------------------------------------===//1617#include "llvm/ADT/APFloat.h"18#include "llvm/ADT/APInt.h"19#include "llvm/ADT/ArrayRef.h"20#include "llvm/ADT/DenseMap.h"21#include "llvm/ADT/STLExtras.h"22#include "llvm/ADT/SetVector.h"23#include "llvm/ADT/SmallPtrSet.h"24#include "llvm/ADT/SmallString.h"25#include "llvm/ADT/SmallVector.h"26#include "llvm/ADT/StringExtras.h"27#include "llvm/ADT/StringRef.h"28#include "llvm/ADT/iterator_range.h"29#include "llvm/BinaryFormat/Dwarf.h"30#include "llvm/Config/llvm-config.h"31#include "llvm/IR/Argument.h"32#include "llvm/IR/AssemblyAnnotationWriter.h"33#include "llvm/IR/Attributes.h"34#include "llvm/IR/BasicBlock.h"35#include "llvm/IR/CFG.h"36#include "llvm/IR/CallingConv.h"37#include "llvm/IR/Comdat.h"38#include "llvm/IR/Constant.h"39#include "llvm/IR/Constants.h"40#include "llvm/IR/DebugInfoMetadata.h"41#include "llvm/IR/DebugProgramInstruction.h"42#include "llvm/IR/DerivedTypes.h"43#include "llvm/IR/Function.h"44#include "llvm/IR/GlobalAlias.h"45#include "llvm/IR/GlobalIFunc.h"46#include "llvm/IR/GlobalObject.h"47#include "llvm/IR/GlobalValue.h"48#include "llvm/IR/GlobalVariable.h"49#include "llvm/IR/IRPrintingPasses.h"50#include "llvm/IR/InlineAsm.h"51#include "llvm/IR/InstrTypes.h"52#include "llvm/IR/Instruction.h"53#include "llvm/IR/Instructions.h"54#include "llvm/IR/IntrinsicInst.h"55#include "llvm/IR/LLVMContext.h"56#include "llvm/IR/Metadata.h"57#include "llvm/IR/Module.h"58#include "llvm/IR/ModuleSlotTracker.h"59#include "llvm/IR/ModuleSummaryIndex.h"60#include "llvm/IR/Operator.h"61#include "llvm/IR/Type.h"62#include "llvm/IR/TypeFinder.h"63#include "llvm/IR/TypedPointerType.h"64#include "llvm/IR/Use.h"65#include "llvm/IR/User.h"66#include "llvm/IR/Value.h"67#include "llvm/Support/AtomicOrdering.h"68#include "llvm/Support/Casting.h"69#include "llvm/Support/Compiler.h"70#include "llvm/Support/Debug.h"71#include "llvm/Support/ErrorHandling.h"72#include "llvm/Support/Format.h"73#include "llvm/Support/FormattedStream.h"74#include "llvm/Support/SaveAndRestore.h"75#include "llvm/Support/raw_ostream.h"76#include <algorithm>77#include <cassert>78#include <cctype>79#include <cstddef>80#include <cstdint>81#include <iterator>82#include <memory>83#include <optional>84#include <string>85#include <tuple>86#include <utility>87#include <vector>8889using namespace llvm;9091// Make virtual table appear in this compilation unit.92AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;9394//===----------------------------------------------------------------------===//95// Helper Functions96//===----------------------------------------------------------------------===//9798using OrderMap = MapVector<const Value *, unsigned>;99100using UseListOrderMap =101DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;102103/// Look for a value that might be wrapped as metadata, e.g. a value in a104/// metadata operand. Returns the input value as-is if it is not wrapped.105static const Value *skipMetadataWrapper(const Value *V) {106if (const auto *MAV = dyn_cast<MetadataAsValue>(V))107if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))108return VAM->getValue();109return V;110}111112static void orderValue(const Value *V, OrderMap &OM) {113if (OM.lookup(V))114return;115116if (const Constant *C = dyn_cast<Constant>(V))117if (C->getNumOperands() && !isa<GlobalValue>(C))118for (const Value *Op : C->operands())119if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))120orderValue(Op, OM);121122// Note: we cannot cache this lookup above, since inserting into the map123// changes the map's size, and thus affects the other IDs.124unsigned ID = OM.size() + 1;125OM[V] = ID;126}127128static OrderMap orderModule(const Module *M) {129OrderMap OM;130131for (const GlobalVariable &G : M->globals()) {132if (G.hasInitializer())133if (!isa<GlobalValue>(G.getInitializer()))134orderValue(G.getInitializer(), OM);135orderValue(&G, OM);136}137for (const GlobalAlias &A : M->aliases()) {138if (!isa<GlobalValue>(A.getAliasee()))139orderValue(A.getAliasee(), OM);140orderValue(&A, OM);141}142for (const GlobalIFunc &I : M->ifuncs()) {143if (!isa<GlobalValue>(I.getResolver()))144orderValue(I.getResolver(), OM);145orderValue(&I, OM);146}147for (const Function &F : *M) {148for (const Use &U : F.operands())149if (!isa<GlobalValue>(U.get()))150orderValue(U.get(), OM);151152orderValue(&F, OM);153154if (F.isDeclaration())155continue;156157for (const Argument &A : F.args())158orderValue(&A, OM);159for (const BasicBlock &BB : F) {160orderValue(&BB, OM);161for (const Instruction &I : BB) {162for (const Value *Op : I.operands()) {163Op = skipMetadataWrapper(Op);164if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||165isa<InlineAsm>(*Op))166orderValue(Op, OM);167}168orderValue(&I, OM);169}170}171}172return OM;173}174175static std::vector<unsigned>176predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {177// Predict use-list order for this one.178using Entry = std::pair<const Use *, unsigned>;179SmallVector<Entry, 64> List;180for (const Use &U : V->uses())181// Check if this user will be serialized.182if (OM.lookup(U.getUser()))183List.push_back(std::make_pair(&U, List.size()));184185if (List.size() < 2)186// We may have lost some users.187return {};188189// When referencing a value before its declaration, a temporary value is190// created, which will later be RAUWed with the actual value. This reverses191// the use list. This happens for all values apart from basic blocks.192bool GetsReversed = !isa<BasicBlock>(V);193if (auto *BA = dyn_cast<BlockAddress>(V))194ID = OM.lookup(BA->getBasicBlock());195llvm::sort(List, [&](const Entry &L, const Entry &R) {196const Use *LU = L.first;197const Use *RU = R.first;198if (LU == RU)199return false;200201auto LID = OM.lookup(LU->getUser());202auto RID = OM.lookup(RU->getUser());203204// If ID is 4, then expect: 7 6 5 1 2 3.205if (LID < RID) {206if (GetsReversed)207if (RID <= ID)208return true;209return false;210}211if (RID < LID) {212if (GetsReversed)213if (LID <= ID)214return false;215return true;216}217218// LID and RID are equal, so we have different operands of the same user.219// Assume operands are added in order for all instructions.220if (GetsReversed)221if (LID <= ID)222return LU->getOperandNo() < RU->getOperandNo();223return LU->getOperandNo() > RU->getOperandNo();224});225226if (llvm::is_sorted(List, llvm::less_second()))227// Order is already correct.228return {};229230// Store the shuffle.231std::vector<unsigned> Shuffle(List.size());232for (size_t I = 0, E = List.size(); I != E; ++I)233Shuffle[I] = List[I].second;234return Shuffle;235}236237static UseListOrderMap predictUseListOrder(const Module *M) {238OrderMap OM = orderModule(M);239UseListOrderMap ULOM;240for (const auto &Pair : OM) {241const Value *V = Pair.first;242if (V->use_empty() || std::next(V->use_begin()) == V->use_end())243continue;244245std::vector<unsigned> Shuffle =246predictValueUseListOrder(V, Pair.second, OM);247if (Shuffle.empty())248continue;249250const Function *F = nullptr;251if (auto *I = dyn_cast<Instruction>(V))252F = I->getFunction();253if (auto *A = dyn_cast<Argument>(V))254F = A->getParent();255if (auto *BB = dyn_cast<BasicBlock>(V))256F = BB->getParent();257ULOM[F][V] = std::move(Shuffle);258}259return ULOM;260}261262static const Module *getModuleFromVal(const Value *V) {263if (const Argument *MA = dyn_cast<Argument>(V))264return MA->getParent() ? MA->getParent()->getParent() : nullptr;265266if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))267return BB->getParent() ? BB->getParent()->getParent() : nullptr;268269if (const Instruction *I = dyn_cast<Instruction>(V)) {270const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;271return M ? M->getParent() : nullptr;272}273274if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))275return GV->getParent();276277if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {278for (const User *U : MAV->users())279if (isa<Instruction>(U))280if (const Module *M = getModuleFromVal(U))281return M;282return nullptr;283}284285return nullptr;286}287288static const Module *getModuleFromDPI(const DbgMarker *Marker) {289const Function *M =290Marker->getParent() ? Marker->getParent()->getParent() : nullptr;291return M ? M->getParent() : nullptr;292}293294static const Module *getModuleFromDPI(const DbgRecord *DR) {295return DR->getMarker() ? getModuleFromDPI(DR->getMarker()) : nullptr;296}297298static void PrintCallingConv(unsigned cc, raw_ostream &Out) {299switch (cc) {300default: Out << "cc" << cc; break;301case CallingConv::Fast: Out << "fastcc"; break;302case CallingConv::Cold: Out << "coldcc"; break;303case CallingConv::AnyReg: Out << "anyregcc"; break;304case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;305case CallingConv::PreserveAll: Out << "preserve_allcc"; break;306case CallingConv::PreserveNone: Out << "preserve_nonecc"; break;307case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;308case CallingConv::GHC: Out << "ghccc"; break;309case CallingConv::Tail: Out << "tailcc"; break;310case CallingConv::GRAAL: Out << "graalcc"; break;311case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;312case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;313case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;314case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;315case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;316case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;317case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;318case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;319case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;320case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;321case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;322case CallingConv::AArch64_SVE_VectorCall:323Out << "aarch64_sve_vector_pcs";324break;325case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:326Out << "aarch64_sme_preservemost_from_x0";327break;328case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1:329Out << "aarch64_sme_preservemost_from_x1";330break;331case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:332Out << "aarch64_sme_preservemost_from_x2";333break;334case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;335case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;336case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;337case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;338case CallingConv::PTX_Device: Out << "ptx_device"; break;339case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;340case CallingConv::Win64: Out << "win64cc"; break;341case CallingConv::SPIR_FUNC: Out << "spir_func"; break;342case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;343case CallingConv::Swift: Out << "swiftcc"; break;344case CallingConv::SwiftTail: Out << "swifttailcc"; break;345case CallingConv::X86_INTR: Out << "x86_intrcc"; break;346case CallingConv::DUMMY_HHVM:347Out << "hhvmcc";348break;349case CallingConv::DUMMY_HHVM_C:350Out << "hhvm_ccc";351break;352case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;353case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;354case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;355case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;356case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;357case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;358case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;359case CallingConv::AMDGPU_CS_Chain:360Out << "amdgpu_cs_chain";361break;362case CallingConv::AMDGPU_CS_ChainPreserve:363Out << "amdgpu_cs_chain_preserve";364break;365case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;366case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;367case CallingConv::M68k_RTD: Out << "m68k_rtdcc"; break;368case CallingConv::RISCV_VectorCall:369Out << "riscv_vector_cc";370break;371}372}373374enum PrefixType {375GlobalPrefix,376ComdatPrefix,377LabelPrefix,378LocalPrefix,379NoPrefix380};381382void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {383assert(!Name.empty() && "Cannot get empty name!");384385// Scan the name to see if it needs quotes first.386bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));387if (!NeedsQuotes) {388for (unsigned char C : Name) {389// By making this unsigned, the value passed in to isalnum will always be390// in the range 0-255. This is important when building with MSVC because391// its implementation will assert. This situation can arise when dealing392// with UTF-8 multibyte characters.393if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&394C != '_') {395NeedsQuotes = true;396break;397}398}399}400401// If we didn't need any quotes, just write out the name in one blast.402if (!NeedsQuotes) {403OS << Name;404return;405}406407// Okay, we need quotes. Output the quotes and escape any scary characters as408// needed.409OS << '"';410printEscapedString(Name, OS);411OS << '"';412}413414/// Turn the specified name into an 'LLVM name', which is either prefixed with %415/// (if the string only contains simple characters) or is surrounded with ""'s416/// (if it has special chars in it). Print it out.417static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {418switch (Prefix) {419case NoPrefix:420break;421case GlobalPrefix:422OS << '@';423break;424case ComdatPrefix:425OS << '$';426break;427case LabelPrefix:428break;429case LocalPrefix:430OS << '%';431break;432}433printLLVMNameWithoutPrefix(OS, Name);434}435436/// Turn the specified name into an 'LLVM name', which is either prefixed with %437/// (if the string only contains simple characters) or is surrounded with ""'s438/// (if it has special chars in it). Print it out.439static void PrintLLVMName(raw_ostream &OS, const Value *V) {440PrintLLVMName(OS, V->getName(),441isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);442}443444static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {445Out << ", <";446if (isa<ScalableVectorType>(Ty))447Out << "vscale x ";448Out << Mask.size() << " x i32> ";449bool FirstElt = true;450if (all_of(Mask, [](int Elt) { return Elt == 0; })) {451Out << "zeroinitializer";452} else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {453Out << "poison";454} else {455Out << "<";456for (int Elt : Mask) {457if (FirstElt)458FirstElt = false;459else460Out << ", ";461Out << "i32 ";462if (Elt == PoisonMaskElem)463Out << "poison";464else465Out << Elt;466}467Out << ">";468}469}470471namespace {472473class TypePrinting {474public:475TypePrinting(const Module *M = nullptr) : DeferredM(M) {}476477TypePrinting(const TypePrinting &) = delete;478TypePrinting &operator=(const TypePrinting &) = delete;479480/// The named types that are used by the current module.481TypeFinder &getNamedTypes();482483/// The numbered types, number to type mapping.484std::vector<StructType *> &getNumberedTypes();485486bool empty();487488void print(Type *Ty, raw_ostream &OS);489490void printStructBody(StructType *Ty, raw_ostream &OS);491492private:493void incorporateTypes();494495/// A module to process lazily when needed. Set to nullptr as soon as used.496const Module *DeferredM;497498TypeFinder NamedTypes;499500// The numbered types, along with their value.501DenseMap<StructType *, unsigned> Type2Number;502503std::vector<StructType *> NumberedTypes;504};505506} // end anonymous namespace507508TypeFinder &TypePrinting::getNamedTypes() {509incorporateTypes();510return NamedTypes;511}512513std::vector<StructType *> &TypePrinting::getNumberedTypes() {514incorporateTypes();515516// We know all the numbers that each type is used and we know that it is a517// dense assignment. Convert the map to an index table, if it's not done518// already (judging from the sizes):519if (NumberedTypes.size() == Type2Number.size())520return NumberedTypes;521522NumberedTypes.resize(Type2Number.size());523for (const auto &P : Type2Number) {524assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");525assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");526NumberedTypes[P.second] = P.first;527}528return NumberedTypes;529}530531bool TypePrinting::empty() {532incorporateTypes();533return NamedTypes.empty() && Type2Number.empty();534}535536void TypePrinting::incorporateTypes() {537if (!DeferredM)538return;539540NamedTypes.run(*DeferredM, false);541DeferredM = nullptr;542543// The list of struct types we got back includes all the struct types, split544// the unnamed ones out to a numbering and remove the anonymous structs.545unsigned NextNumber = 0;546547std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();548for (StructType *STy : NamedTypes) {549// Ignore anonymous types.550if (STy->isLiteral())551continue;552553if (STy->getName().empty())554Type2Number[STy] = NextNumber++;555else556*NextToUse++ = STy;557}558559NamedTypes.erase(NextToUse, NamedTypes.end());560}561562/// Write the specified type to the specified raw_ostream, making use of type563/// names or up references to shorten the type name where possible.564void TypePrinting::print(Type *Ty, raw_ostream &OS) {565switch (Ty->getTypeID()) {566case Type::VoidTyID: OS << "void"; return;567case Type::HalfTyID: OS << "half"; return;568case Type::BFloatTyID: OS << "bfloat"; return;569case Type::FloatTyID: OS << "float"; return;570case Type::DoubleTyID: OS << "double"; return;571case Type::X86_FP80TyID: OS << "x86_fp80"; return;572case Type::FP128TyID: OS << "fp128"; return;573case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;574case Type::LabelTyID: OS << "label"; return;575case Type::MetadataTyID: OS << "metadata"; return;576case Type::X86_MMXTyID: OS << "x86_mmx"; return;577case Type::X86_AMXTyID: OS << "x86_amx"; return;578case Type::TokenTyID: OS << "token"; return;579case Type::IntegerTyID:580OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();581return;582583case Type::FunctionTyID: {584FunctionType *FTy = cast<FunctionType>(Ty);585print(FTy->getReturnType(), OS);586OS << " (";587ListSeparator LS;588for (Type *Ty : FTy->params()) {589OS << LS;590print(Ty, OS);591}592if (FTy->isVarArg())593OS << LS << "...";594OS << ')';595return;596}597case Type::StructTyID: {598StructType *STy = cast<StructType>(Ty);599600if (STy->isLiteral())601return printStructBody(STy, OS);602603if (!STy->getName().empty())604return PrintLLVMName(OS, STy->getName(), LocalPrefix);605606incorporateTypes();607const auto I = Type2Number.find(STy);608if (I != Type2Number.end())609OS << '%' << I->second;610else // Not enumerated, print the hex address.611OS << "%\"type " << STy << '\"';612return;613}614case Type::PointerTyID: {615PointerType *PTy = cast<PointerType>(Ty);616OS << "ptr";617if (unsigned AddressSpace = PTy->getAddressSpace())618OS << " addrspace(" << AddressSpace << ')';619return;620}621case Type::ArrayTyID: {622ArrayType *ATy = cast<ArrayType>(Ty);623OS << '[' << ATy->getNumElements() << " x ";624print(ATy->getElementType(), OS);625OS << ']';626return;627}628case Type::FixedVectorTyID:629case Type::ScalableVectorTyID: {630VectorType *PTy = cast<VectorType>(Ty);631ElementCount EC = PTy->getElementCount();632OS << "<";633if (EC.isScalable())634OS << "vscale x ";635OS << EC.getKnownMinValue() << " x ";636print(PTy->getElementType(), OS);637OS << '>';638return;639}640case Type::TypedPointerTyID: {641TypedPointerType *TPTy = cast<TypedPointerType>(Ty);642OS << "typedptr(" << *TPTy->getElementType() << ", "643<< TPTy->getAddressSpace() << ")";644return;645}646case Type::TargetExtTyID:647TargetExtType *TETy = cast<TargetExtType>(Ty);648OS << "target(\"";649printEscapedString(Ty->getTargetExtName(), OS);650OS << "\"";651for (Type *Inner : TETy->type_params())652OS << ", " << *Inner;653for (unsigned IntParam : TETy->int_params())654OS << ", " << IntParam;655OS << ")";656return;657}658llvm_unreachable("Invalid TypeID");659}660661void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {662if (STy->isOpaque()) {663OS << "opaque";664return;665}666667if (STy->isPacked())668OS << '<';669670if (STy->getNumElements() == 0) {671OS << "{}";672} else {673OS << "{ ";674ListSeparator LS;675for (Type *Ty : STy->elements()) {676OS << LS;677print(Ty, OS);678}679680OS << " }";681}682if (STy->isPacked())683OS << '>';684}685686AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;687688namespace llvm {689690//===----------------------------------------------------------------------===//691// SlotTracker Class: Enumerate slot numbers for unnamed values692//===----------------------------------------------------------------------===//693/// This class provides computation of slot numbers for LLVM Assembly writing.694///695class SlotTracker : public AbstractSlotTrackerStorage {696public:697/// ValueMap - A mapping of Values to slot numbers.698using ValueMap = DenseMap<const Value *, unsigned>;699700private:701/// TheModule - The module for which we are holding slot numbers.702const Module* TheModule;703704/// TheFunction - The function for which we are holding slot numbers.705const Function* TheFunction = nullptr;706bool FunctionProcessed = false;707bool ShouldInitializeAllMetadata;708709std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>710ProcessModuleHookFn;711std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>712ProcessFunctionHookFn;713714/// The summary index for which we are holding slot numbers.715const ModuleSummaryIndex *TheIndex = nullptr;716717/// mMap - The slot map for the module level data.718ValueMap mMap;719unsigned mNext = 0;720721/// fMap - The slot map for the function level data.722ValueMap fMap;723unsigned fNext = 0;724725/// mdnMap - Map for MDNodes.726DenseMap<const MDNode*, unsigned> mdnMap;727unsigned mdnNext = 0;728729/// asMap - The slot map for attribute sets.730DenseMap<AttributeSet, unsigned> asMap;731unsigned asNext = 0;732733/// ModulePathMap - The slot map for Module paths used in the summary index.734StringMap<unsigned> ModulePathMap;735unsigned ModulePathNext = 0;736737/// GUIDMap - The slot map for GUIDs used in the summary index.738DenseMap<GlobalValue::GUID, unsigned> GUIDMap;739unsigned GUIDNext = 0;740741/// TypeIdMap - The slot map for type ids used in the summary index.742StringMap<unsigned> TypeIdMap;743unsigned TypeIdNext = 0;744745/// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids746/// used in the summary index.747StringMap<unsigned> TypeIdCompatibleVtableMap;748unsigned TypeIdCompatibleVtableNext = 0;749750public:751/// Construct from a module.752///753/// If \c ShouldInitializeAllMetadata, initializes all metadata in all754/// functions, giving correct numbering for metadata referenced only from755/// within a function (even if no functions have been initialized).756explicit SlotTracker(const Module *M,757bool ShouldInitializeAllMetadata = false);758759/// Construct from a function, starting out in incorp state.760///761/// If \c ShouldInitializeAllMetadata, initializes all metadata in all762/// functions, giving correct numbering for metadata referenced only from763/// within a function (even if no functions have been initialized).764explicit SlotTracker(const Function *F,765bool ShouldInitializeAllMetadata = false);766767/// Construct from a module summary index.768explicit SlotTracker(const ModuleSummaryIndex *Index);769770SlotTracker(const SlotTracker &) = delete;771SlotTracker &operator=(const SlotTracker &) = delete;772773~SlotTracker() = default;774775void setProcessHook(776std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);777void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,778const Function *, bool)>);779780unsigned getNextMetadataSlot() override { return mdnNext; }781782void createMetadataSlot(const MDNode *N) override;783784/// Return the slot number of the specified value in it's type785/// plane. If something is not in the SlotTracker, return -1.786int getLocalSlot(const Value *V);787int getGlobalSlot(const GlobalValue *V);788int getMetadataSlot(const MDNode *N) override;789int getAttributeGroupSlot(AttributeSet AS);790int getModulePathSlot(StringRef Path);791int getGUIDSlot(GlobalValue::GUID GUID);792int getTypeIdSlot(StringRef Id);793int getTypeIdCompatibleVtableSlot(StringRef Id);794795/// If you'd like to deal with a function instead of just a module, use796/// this method to get its data into the SlotTracker.797void incorporateFunction(const Function *F) {798TheFunction = F;799FunctionProcessed = false;800}801802const Function *getFunction() const { return TheFunction; }803804/// After calling incorporateFunction, use this method to remove the805/// most recently incorporated function from the SlotTracker. This806/// will reset the state of the machine back to just the module contents.807void purgeFunction();808809/// MDNode map iterators.810using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;811812mdn_iterator mdn_begin() { return mdnMap.begin(); }813mdn_iterator mdn_end() { return mdnMap.end(); }814unsigned mdn_size() const { return mdnMap.size(); }815bool mdn_empty() const { return mdnMap.empty(); }816817/// AttributeSet map iterators.818using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;819820as_iterator as_begin() { return asMap.begin(); }821as_iterator as_end() { return asMap.end(); }822unsigned as_size() const { return asMap.size(); }823bool as_empty() const { return asMap.empty(); }824825/// GUID map iterators.826using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;827828/// These functions do the actual initialization.829inline void initializeIfNeeded();830int initializeIndexIfNeeded();831832// Implementation Details833private:834/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.835void CreateModuleSlot(const GlobalValue *V);836837/// CreateMetadataSlot - Insert the specified MDNode* into the slot table.838void CreateMetadataSlot(const MDNode *N);839840/// CreateFunctionSlot - Insert the specified Value* into the slot table.841void CreateFunctionSlot(const Value *V);842843/// Insert the specified AttributeSet into the slot table.844void CreateAttributeSetSlot(AttributeSet AS);845846inline void CreateModulePathSlot(StringRef Path);847void CreateGUIDSlot(GlobalValue::GUID GUID);848void CreateTypeIdSlot(StringRef Id);849void CreateTypeIdCompatibleVtableSlot(StringRef Id);850851/// Add all of the module level global variables (and their initializers)852/// and function declarations, but not the contents of those functions.853void processModule();854// Returns number of allocated slots855int processIndex();856857/// Add all of the functions arguments, basic blocks, and instructions.858void processFunction();859860/// Add the metadata directly attached to a GlobalObject.861void processGlobalObjectMetadata(const GlobalObject &GO);862863/// Add all of the metadata from a function.864void processFunctionMetadata(const Function &F);865866/// Add all of the metadata from an instruction.867void processInstructionMetadata(const Instruction &I);868869/// Add all of the metadata from a DbgRecord.870void processDbgRecordMetadata(const DbgRecord &DVR);871};872873} // end namespace llvm874875ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,876const Function *F)877: M(M), F(F), Machine(&Machine) {}878879ModuleSlotTracker::ModuleSlotTracker(const Module *M,880bool ShouldInitializeAllMetadata)881: ShouldCreateStorage(M),882ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}883884ModuleSlotTracker::~ModuleSlotTracker() = default;885886SlotTracker *ModuleSlotTracker::getMachine() {887if (!ShouldCreateStorage)888return Machine;889890ShouldCreateStorage = false;891MachineStorage =892std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);893Machine = MachineStorage.get();894if (ProcessModuleHookFn)895Machine->setProcessHook(ProcessModuleHookFn);896if (ProcessFunctionHookFn)897Machine->setProcessHook(ProcessFunctionHookFn);898return Machine;899}900901void ModuleSlotTracker::incorporateFunction(const Function &F) {902// Using getMachine() may lazily create the slot tracker.903if (!getMachine())904return;905906// Nothing to do if this is the right function already.907if (this->F == &F)908return;909if (this->F)910Machine->purgeFunction();911Machine->incorporateFunction(&F);912this->F = &F;913}914915int ModuleSlotTracker::getLocalSlot(const Value *V) {916assert(F && "No function incorporated");917return Machine->getLocalSlot(V);918}919920void ModuleSlotTracker::setProcessHook(921std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>922Fn) {923ProcessModuleHookFn = Fn;924}925926void ModuleSlotTracker::setProcessHook(927std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>928Fn) {929ProcessFunctionHookFn = Fn;930}931932static SlotTracker *createSlotTracker(const Value *V) {933if (const Argument *FA = dyn_cast<Argument>(V))934return new SlotTracker(FA->getParent());935936if (const Instruction *I = dyn_cast<Instruction>(V))937if (I->getParent())938return new SlotTracker(I->getParent()->getParent());939940if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))941return new SlotTracker(BB->getParent());942943if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))944return new SlotTracker(GV->getParent());945946if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))947return new SlotTracker(GA->getParent());948949if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))950return new SlotTracker(GIF->getParent());951952if (const Function *Func = dyn_cast<Function>(V))953return new SlotTracker(Func);954955return nullptr;956}957958#if 0959#define ST_DEBUG(X) dbgs() << X960#else961#define ST_DEBUG(X)962#endif963964// Module level constructor. Causes the contents of the Module (sans functions)965// to be added to the slot table.966SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)967: TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}968969// Function level constructor. Causes the contents of the Module and the one970// function provided to be added to the slot table.971SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)972: TheModule(F ? F->getParent() : nullptr), TheFunction(F),973ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}974975SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)976: TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}977978inline void SlotTracker::initializeIfNeeded() {979if (TheModule) {980processModule();981TheModule = nullptr; ///< Prevent re-processing next time we're called.982}983984if (TheFunction && !FunctionProcessed)985processFunction();986}987988int SlotTracker::initializeIndexIfNeeded() {989if (!TheIndex)990return 0;991int NumSlots = processIndex();992TheIndex = nullptr; ///< Prevent re-processing next time we're called.993return NumSlots;994}995996// Iterate through all the global variables, functions, and global997// variable initializers and create slots for them.998void SlotTracker::processModule() {999ST_DEBUG("begin processModule!\n");10001001// Add all of the unnamed global variables to the value table.1002for (const GlobalVariable &Var : TheModule->globals()) {1003if (!Var.hasName())1004CreateModuleSlot(&Var);1005processGlobalObjectMetadata(Var);1006auto Attrs = Var.getAttributes();1007if (Attrs.hasAttributes())1008CreateAttributeSetSlot(Attrs);1009}10101011for (const GlobalAlias &A : TheModule->aliases()) {1012if (!A.hasName())1013CreateModuleSlot(&A);1014}10151016for (const GlobalIFunc &I : TheModule->ifuncs()) {1017if (!I.hasName())1018CreateModuleSlot(&I);1019}10201021// Add metadata used by named metadata.1022for (const NamedMDNode &NMD : TheModule->named_metadata()) {1023for (const MDNode *N : NMD.operands())1024CreateMetadataSlot(N);1025}10261027for (const Function &F : *TheModule) {1028if (!F.hasName())1029// Add all the unnamed functions to the table.1030CreateModuleSlot(&F);10311032if (ShouldInitializeAllMetadata)1033processFunctionMetadata(F);10341035// Add all the function attributes to the table.1036// FIXME: Add attributes of other objects?1037AttributeSet FnAttrs = F.getAttributes().getFnAttrs();1038if (FnAttrs.hasAttributes())1039CreateAttributeSetSlot(FnAttrs);1040}10411042if (ProcessModuleHookFn)1043ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);10441045ST_DEBUG("end processModule!\n");1046}10471048// Process the arguments, basic blocks, and instructions of a function.1049void SlotTracker::processFunction() {1050ST_DEBUG("begin processFunction!\n");1051fNext = 0;10521053// Process function metadata if it wasn't hit at the module-level.1054if (!ShouldInitializeAllMetadata)1055processFunctionMetadata(*TheFunction);10561057// Add all the function arguments with no names.1058for(Function::const_arg_iterator AI = TheFunction->arg_begin(),1059AE = TheFunction->arg_end(); AI != AE; ++AI)1060if (!AI->hasName())1061CreateFunctionSlot(&*AI);10621063ST_DEBUG("Inserting Instructions:\n");10641065// Add all of the basic blocks and instructions with no names.1066for (auto &BB : *TheFunction) {1067if (!BB.hasName())1068CreateFunctionSlot(&BB);10691070for (auto &I : BB) {1071if (!I.getType()->isVoidTy() && !I.hasName())1072CreateFunctionSlot(&I);10731074// We allow direct calls to any llvm.foo function here, because the1075// target may not be linked into the optimizer.1076if (const auto *Call = dyn_cast<CallBase>(&I)) {1077// Add all the call attributes to the table.1078AttributeSet Attrs = Call->getAttributes().getFnAttrs();1079if (Attrs.hasAttributes())1080CreateAttributeSetSlot(Attrs);1081}1082}1083}10841085if (ProcessFunctionHookFn)1086ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);10871088FunctionProcessed = true;10891090ST_DEBUG("end processFunction!\n");1091}10921093// Iterate through all the GUID in the index and create slots for them.1094int SlotTracker::processIndex() {1095ST_DEBUG("begin processIndex!\n");1096assert(TheIndex);10971098// The first block of slots are just the module ids, which start at 0 and are1099// assigned consecutively. Since the StringMap iteration order isn't1100// guaranteed, order by path string before assigning slots.1101std::vector<StringRef> ModulePaths;1102for (auto &[ModPath, _] : TheIndex->modulePaths())1103ModulePaths.push_back(ModPath);1104llvm::sort(ModulePaths.begin(), ModulePaths.end());1105for (auto &ModPath : ModulePaths)1106CreateModulePathSlot(ModPath);11071108// Start numbering the GUIDs after the module ids.1109GUIDNext = ModulePathNext;11101111for (auto &GlobalList : *TheIndex)1112CreateGUIDSlot(GlobalList.first);11131114// Start numbering the TypeIdCompatibleVtables after the GUIDs.1115TypeIdCompatibleVtableNext = GUIDNext;1116for (auto &TId : TheIndex->typeIdCompatibleVtableMap())1117CreateTypeIdCompatibleVtableSlot(TId.first);11181119// Start numbering the TypeIds after the TypeIdCompatibleVtables.1120TypeIdNext = TypeIdCompatibleVtableNext;1121for (const auto &TID : TheIndex->typeIds())1122CreateTypeIdSlot(TID.second.first);11231124ST_DEBUG("end processIndex!\n");1125return TypeIdNext;1126}11271128void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {1129SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;1130GO.getAllMetadata(MDs);1131for (auto &MD : MDs)1132CreateMetadataSlot(MD.second);1133}11341135void SlotTracker::processFunctionMetadata(const Function &F) {1136processGlobalObjectMetadata(F);1137for (auto &BB : F) {1138for (auto &I : BB) {1139for (const DbgRecord &DR : I.getDbgRecordRange())1140processDbgRecordMetadata(DR);1141processInstructionMetadata(I);1142}1143}1144}11451146void SlotTracker::processDbgRecordMetadata(const DbgRecord &DR) {1147if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR)) {1148// Process metadata used by DbgRecords; we only specifically care about the1149// DILocalVariable, DILocation, and DIAssignID fields, as the Value and1150// Expression fields should only be printed inline and so do not use a slot.1151// Note: The above doesn't apply for empty-metadata operands.1152if (auto *Empty = dyn_cast<MDNode>(DVR->getRawLocation()))1153CreateMetadataSlot(Empty);1154CreateMetadataSlot(DVR->getRawVariable());1155if (DVR->isDbgAssign()) {1156CreateMetadataSlot(cast<MDNode>(DVR->getRawAssignID()));1157if (auto *Empty = dyn_cast<MDNode>(DVR->getRawAddress()))1158CreateMetadataSlot(Empty);1159}1160} else if (const DbgLabelRecord *DLR = dyn_cast<const DbgLabelRecord>(&DR)) {1161CreateMetadataSlot(DLR->getRawLabel());1162} else {1163llvm_unreachable("unsupported DbgRecord kind");1164}1165CreateMetadataSlot(DR.getDebugLoc().getAsMDNode());1166}11671168void SlotTracker::processInstructionMetadata(const Instruction &I) {1169// Process metadata used directly by intrinsics.1170if (const CallInst *CI = dyn_cast<CallInst>(&I))1171if (Function *F = CI->getCalledFunction())1172if (F->isIntrinsic())1173for (auto &Op : I.operands())1174if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))1175if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))1176CreateMetadataSlot(N);11771178// Process metadata attached to this instruction.1179SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;1180I.getAllMetadata(MDs);1181for (auto &MD : MDs)1182CreateMetadataSlot(MD.second);1183}11841185/// Clean up after incorporating a function. This is the only way to get out of1186/// the function incorporation state that affects get*Slot/Create*Slot. Function1187/// incorporation state is indicated by TheFunction != 0.1188void SlotTracker::purgeFunction() {1189ST_DEBUG("begin purgeFunction!\n");1190fMap.clear(); // Simply discard the function level map1191TheFunction = nullptr;1192FunctionProcessed = false;1193ST_DEBUG("end purgeFunction!\n");1194}11951196/// getGlobalSlot - Get the slot number of a global value.1197int SlotTracker::getGlobalSlot(const GlobalValue *V) {1198// Check for uninitialized state and do lazy initialization.1199initializeIfNeeded();12001201// Find the value in the module map1202ValueMap::iterator MI = mMap.find(V);1203return MI == mMap.end() ? -1 : (int)MI->second;1204}12051206void SlotTracker::setProcessHook(1207std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>1208Fn) {1209ProcessModuleHookFn = Fn;1210}12111212void SlotTracker::setProcessHook(1213std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>1214Fn) {1215ProcessFunctionHookFn = Fn;1216}12171218/// getMetadataSlot - Get the slot number of a MDNode.1219void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }12201221/// getMetadataSlot - Get the slot number of a MDNode.1222int SlotTracker::getMetadataSlot(const MDNode *N) {1223// Check for uninitialized state and do lazy initialization.1224initializeIfNeeded();12251226// Find the MDNode in the module map1227mdn_iterator MI = mdnMap.find(N);1228return MI == mdnMap.end() ? -1 : (int)MI->second;1229}12301231/// getLocalSlot - Get the slot number for a value that is local to a function.1232int SlotTracker::getLocalSlot(const Value *V) {1233assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");12341235// Check for uninitialized state and do lazy initialization.1236initializeIfNeeded();12371238ValueMap::iterator FI = fMap.find(V);1239return FI == fMap.end() ? -1 : (int)FI->second;1240}12411242int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {1243// Check for uninitialized state and do lazy initialization.1244initializeIfNeeded();12451246// Find the AttributeSet in the module map.1247as_iterator AI = asMap.find(AS);1248return AI == asMap.end() ? -1 : (int)AI->second;1249}12501251int SlotTracker::getModulePathSlot(StringRef Path) {1252// Check for uninitialized state and do lazy initialization.1253initializeIndexIfNeeded();12541255// Find the Module path in the map1256auto I = ModulePathMap.find(Path);1257return I == ModulePathMap.end() ? -1 : (int)I->second;1258}12591260int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {1261// Check for uninitialized state and do lazy initialization.1262initializeIndexIfNeeded();12631264// Find the GUID in the map1265guid_iterator I = GUIDMap.find(GUID);1266return I == GUIDMap.end() ? -1 : (int)I->second;1267}12681269int SlotTracker::getTypeIdSlot(StringRef Id) {1270// Check for uninitialized state and do lazy initialization.1271initializeIndexIfNeeded();12721273// Find the TypeId string in the map1274auto I = TypeIdMap.find(Id);1275return I == TypeIdMap.end() ? -1 : (int)I->second;1276}12771278int SlotTracker::getTypeIdCompatibleVtableSlot(StringRef Id) {1279// Check for uninitialized state and do lazy initialization.1280initializeIndexIfNeeded();12811282// Find the TypeIdCompatibleVtable string in the map1283auto I = TypeIdCompatibleVtableMap.find(Id);1284return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;1285}12861287/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.1288void SlotTracker::CreateModuleSlot(const GlobalValue *V) {1289assert(V && "Can't insert a null Value into SlotTracker!");1290assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");1291assert(!V->hasName() && "Doesn't need a slot!");12921293unsigned DestSlot = mNext++;1294mMap[V] = DestSlot;12951296ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<1297DestSlot << " [");1298// G = Global, F = Function, A = Alias, I = IFunc, o = other1299ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :1300(isa<Function>(V) ? 'F' :1301(isa<GlobalAlias>(V) ? 'A' :1302(isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");1303}13041305/// CreateSlot - Create a new slot for the specified value if it has no name.1306void SlotTracker::CreateFunctionSlot(const Value *V) {1307assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");13081309unsigned DestSlot = fNext++;1310fMap[V] = DestSlot;13111312// G = Global, F = Function, o = other1313ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<1314DestSlot << " [o]\n");1315}13161317/// CreateModuleSlot - Insert the specified MDNode* into the slot table.1318void SlotTracker::CreateMetadataSlot(const MDNode *N) {1319assert(N && "Can't insert a null Value into SlotTracker!");13201321// Don't make slots for DIExpressions. We just print them inline everywhere.1322if (isa<DIExpression>(N))1323return;13241325unsigned DestSlot = mdnNext;1326if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)1327return;1328++mdnNext;13291330// Recursively add any MDNodes referenced by operands.1331for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)1332if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))1333CreateMetadataSlot(Op);1334}13351336void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {1337assert(AS.hasAttributes() && "Doesn't need a slot!");13381339as_iterator I = asMap.find(AS);1340if (I != asMap.end())1341return;13421343unsigned DestSlot = asNext++;1344asMap[AS] = DestSlot;1345}13461347/// Create a new slot for the specified Module1348void SlotTracker::CreateModulePathSlot(StringRef Path) {1349ModulePathMap[Path] = ModulePathNext++;1350}13511352/// Create a new slot for the specified GUID1353void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {1354GUIDMap[GUID] = GUIDNext++;1355}13561357/// Create a new slot for the specified Id1358void SlotTracker::CreateTypeIdSlot(StringRef Id) {1359TypeIdMap[Id] = TypeIdNext++;1360}13611362/// Create a new slot for the specified Id1363void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {1364TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;1365}13661367namespace {1368/// Common instances used by most of the printer functions.1369struct AsmWriterContext {1370TypePrinting *TypePrinter = nullptr;1371SlotTracker *Machine = nullptr;1372const Module *Context = nullptr;13731374AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)1375: TypePrinter(TP), Machine(ST), Context(M) {}13761377static AsmWriterContext &getEmpty() {1378static AsmWriterContext EmptyCtx(nullptr, nullptr);1379return EmptyCtx;1380}13811382/// A callback that will be triggered when the underlying printer1383/// prints a Metadata as operand.1384virtual void onWriteMetadataAsOperand(const Metadata *) {}13851386virtual ~AsmWriterContext() = default;1387};1388} // end anonymous namespace13891390//===----------------------------------------------------------------------===//1391// AsmWriter Implementation1392//===----------------------------------------------------------------------===//13931394static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,1395AsmWriterContext &WriterCtx);13961397static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,1398AsmWriterContext &WriterCtx,1399bool FromValue = false);14001401static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {1402if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))1403Out << FPO->getFastMathFlags();14041405if (const OverflowingBinaryOperator *OBO =1406dyn_cast<OverflowingBinaryOperator>(U)) {1407if (OBO->hasNoUnsignedWrap())1408Out << " nuw";1409if (OBO->hasNoSignedWrap())1410Out << " nsw";1411} else if (const PossiblyExactOperator *Div =1412dyn_cast<PossiblyExactOperator>(U)) {1413if (Div->isExact())1414Out << " exact";1415} else if (const PossiblyDisjointInst *PDI =1416dyn_cast<PossiblyDisjointInst>(U)) {1417if (PDI->isDisjoint())1418Out << " disjoint";1419} else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {1420if (GEP->isInBounds())1421Out << " inbounds";1422else if (GEP->hasNoUnsignedSignedWrap())1423Out << " nusw";1424if (GEP->hasNoUnsignedWrap())1425Out << " nuw";1426if (auto InRange = GEP->getInRange()) {1427Out << " inrange(" << InRange->getLower() << ", " << InRange->getUpper()1428<< ")";1429}1430} else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(U)) {1431if (NNI->hasNonNeg())1432Out << " nneg";1433} else if (const auto *TI = dyn_cast<TruncInst>(U)) {1434if (TI->hasNoUnsignedWrap())1435Out << " nuw";1436if (TI->hasNoSignedWrap())1437Out << " nsw";1438}1439}14401441static void WriteAPFloatInternal(raw_ostream &Out, const APFloat &APF) {1442if (&APF.getSemantics() == &APFloat::IEEEsingle() ||1443&APF.getSemantics() == &APFloat::IEEEdouble()) {1444// We would like to output the FP constant value in exponential notation,1445// but we cannot do this if doing so will lose precision. Check here to1446// make sure that we only output it in exponential format if we can parse1447// the value back and get the same value.1448//1449bool ignored;1450bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();1451bool isInf = APF.isInfinity();1452bool isNaN = APF.isNaN();14531454if (!isInf && !isNaN) {1455double Val = APF.convertToDouble();1456SmallString<128> StrVal;1457APF.toString(StrVal, 6, 0, false);1458// Check to make sure that the stringized number is not some string like1459// "Inf" or NaN, that atof will accept, but the lexer will not. Check1460// that the string matches the "[-+]?[0-9]" regex.1461//1462assert((isDigit(StrVal[0]) ||1463((StrVal[0] == '-' || StrVal[0] == '+') && isDigit(StrVal[1]))) &&1464"[-+]?[0-9] regex does not match!");1465// Reparse stringized version!1466if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {1467Out << StrVal;1468return;1469}1470}14711472// Otherwise we could not reparse it to exactly the same value, so we must1473// output the string in hexadecimal format! Note that loading and storing1474// floating point types changes the bits of NaNs on some hosts, notably1475// x86, so we must not use these types.1476static_assert(sizeof(double) == sizeof(uint64_t),1477"assuming that double is 64 bits!");1478APFloat apf = APF;14791480// Floats are represented in ASCII IR as double, convert.1481// FIXME: We should allow 32-bit hex float and remove this.1482if (!isDouble) {1483// A signaling NaN is quieted on conversion, so we need to recreate the1484// expected value after convert (quiet bit of the payload is clear).1485bool IsSNAN = apf.isSignaling();1486apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,1487&ignored);1488if (IsSNAN) {1489APInt Payload = apf.bitcastToAPInt();1490apf =1491APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(), &Payload);1492}1493}14941495Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);1496return;1497}14981499// Either half, bfloat or some form of long double.1500// These appear as a magic letter identifying the type, then a1501// fixed number of hex digits.1502Out << "0x";1503APInt API = APF.bitcastToAPInt();1504if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {1505Out << 'K';1506Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,1507/*Upper=*/true);1508Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,1509/*Upper=*/true);1510} else if (&APF.getSemantics() == &APFloat::IEEEquad()) {1511Out << 'L';1512Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,1513/*Upper=*/true);1514Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,1515/*Upper=*/true);1516} else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {1517Out << 'M';1518Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,1519/*Upper=*/true);1520Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,1521/*Upper=*/true);1522} else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {1523Out << 'H';1524Out << format_hex_no_prefix(API.getZExtValue(), 4,1525/*Upper=*/true);1526} else if (&APF.getSemantics() == &APFloat::BFloat()) {1527Out << 'R';1528Out << format_hex_no_prefix(API.getZExtValue(), 4,1529/*Upper=*/true);1530} else1531llvm_unreachable("Unsupported floating point type");1532}15331534static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,1535AsmWriterContext &WriterCtx) {1536if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {1537Type *Ty = CI->getType();15381539if (Ty->isVectorTy()) {1540Out << "splat (";1541WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);1542Out << " ";1543}15441545if (Ty->getScalarType()->isIntegerTy(1))1546Out << (CI->getZExtValue() ? "true" : "false");1547else1548Out << CI->getValue();15491550if (Ty->isVectorTy())1551Out << ")";15521553return;1554}15551556if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {1557Type *Ty = CFP->getType();15581559if (Ty->isVectorTy()) {1560Out << "splat (";1561WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);1562Out << " ";1563}15641565WriteAPFloatInternal(Out, CFP->getValueAPF());15661567if (Ty->isVectorTy())1568Out << ")";15691570return;1571}15721573if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {1574Out << "zeroinitializer";1575return;1576}15771578if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {1579Out << "blockaddress(";1580WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);1581Out << ", ";1582WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);1583Out << ")";1584return;1585}15861587if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {1588Out << "dso_local_equivalent ";1589WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);1590return;1591}15921593if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {1594Out << "no_cfi ";1595WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);1596return;1597}15981599if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV)) {1600Out << "ptrauth (";16011602// ptrauth (ptr CST, i32 KEY[, i64 DISC[, ptr ADDRDISC]?]?)1603unsigned NumOpsToWrite = 2;1604if (!CPA->getOperand(2)->isNullValue())1605NumOpsToWrite = 3;1606if (!CPA->getOperand(3)->isNullValue())1607NumOpsToWrite = 4;16081609ListSeparator LS;1610for (unsigned i = 0, e = NumOpsToWrite; i != e; ++i) {1611Out << LS;1612WriterCtx.TypePrinter->print(CPA->getOperand(i)->getType(), Out);1613Out << ' ';1614WriteAsOperandInternal(Out, CPA->getOperand(i), WriterCtx);1615}1616Out << ')';1617return;1618}16191620if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {1621Type *ETy = CA->getType()->getElementType();1622Out << '[';1623WriterCtx.TypePrinter->print(ETy, Out);1624Out << ' ';1625WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);1626for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {1627Out << ", ";1628WriterCtx.TypePrinter->print(ETy, Out);1629Out << ' ';1630WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);1631}1632Out << ']';1633return;1634}16351636if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {1637// As a special case, print the array as a string if it is an array of1638// i8 with ConstantInt values.1639if (CA->isString()) {1640Out << "c\"";1641printEscapedString(CA->getAsString(), Out);1642Out << '"';1643return;1644}16451646Type *ETy = CA->getType()->getElementType();1647Out << '[';1648WriterCtx.TypePrinter->print(ETy, Out);1649Out << ' ';1650WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);1651for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {1652Out << ", ";1653WriterCtx.TypePrinter->print(ETy, Out);1654Out << ' ';1655WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);1656}1657Out << ']';1658return;1659}16601661if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {1662if (CS->getType()->isPacked())1663Out << '<';1664Out << '{';1665unsigned N = CS->getNumOperands();1666if (N) {1667Out << ' ';1668WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);1669Out << ' ';16701671WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);16721673for (unsigned i = 1; i < N; i++) {1674Out << ", ";1675WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);1676Out << ' ';16771678WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);1679}1680Out << ' ';1681}16821683Out << '}';1684if (CS->getType()->isPacked())1685Out << '>';1686return;1687}16881689if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {1690auto *CVVTy = cast<FixedVectorType>(CV->getType());1691Type *ETy = CVVTy->getElementType();1692Out << '<';1693WriterCtx.TypePrinter->print(ETy, Out);1694Out << ' ';1695WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);1696for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {1697Out << ", ";1698WriterCtx.TypePrinter->print(ETy, Out);1699Out << ' ';1700WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);1701}1702Out << '>';1703return;1704}17051706if (isa<ConstantPointerNull>(CV)) {1707Out << "null";1708return;1709}17101711if (isa<ConstantTokenNone>(CV)) {1712Out << "none";1713return;1714}17151716if (isa<PoisonValue>(CV)) {1717Out << "poison";1718return;1719}17201721if (isa<UndefValue>(CV)) {1722Out << "undef";1723return;1724}17251726if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {1727Out << CE->getOpcodeName();1728WriteOptimizationInfo(Out, CE);1729Out << " (";17301731if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {1732WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);1733Out << ", ";1734}17351736for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end();1737++OI) {1738WriterCtx.TypePrinter->print((*OI)->getType(), Out);1739Out << ' ';1740WriteAsOperandInternal(Out, *OI, WriterCtx);1741if (OI+1 != CE->op_end())1742Out << ", ";1743}17441745if (CE->isCast()) {1746Out << " to ";1747WriterCtx.TypePrinter->print(CE->getType(), Out);1748}17491750if (CE->getOpcode() == Instruction::ShuffleVector)1751PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());17521753Out << ')';1754return;1755}17561757Out << "<placeholder or erroneous Constant>";1758}17591760static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,1761AsmWriterContext &WriterCtx) {1762Out << "!{";1763for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {1764const Metadata *MD = Node->getOperand(mi);1765if (!MD)1766Out << "null";1767else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {1768Value *V = MDV->getValue();1769WriterCtx.TypePrinter->print(V->getType(), Out);1770Out << ' ';1771WriteAsOperandInternal(Out, V, WriterCtx);1772} else {1773WriteAsOperandInternal(Out, MD, WriterCtx);1774WriterCtx.onWriteMetadataAsOperand(MD);1775}1776if (mi + 1 != me)1777Out << ", ";1778}17791780Out << "}";1781}17821783namespace {17841785struct FieldSeparator {1786bool Skip = true;1787const char *Sep;17881789FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}1790};17911792raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {1793if (FS.Skip) {1794FS.Skip = false;1795return OS;1796}1797return OS << FS.Sep;1798}17991800struct MDFieldPrinter {1801raw_ostream &Out;1802FieldSeparator FS;1803AsmWriterContext &WriterCtx;18041805explicit MDFieldPrinter(raw_ostream &Out)1806: Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}1807MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)1808: Out(Out), WriterCtx(Ctx) {}18091810void printTag(const DINode *N);1811void printMacinfoType(const DIMacroNode *N);1812void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);1813void printString(StringRef Name, StringRef Value,1814bool ShouldSkipEmpty = true);1815void printMetadata(StringRef Name, const Metadata *MD,1816bool ShouldSkipNull = true);1817template <class IntTy>1818void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);1819void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,1820bool ShouldSkipZero);1821void printBool(StringRef Name, bool Value,1822std::optional<bool> Default = std::nullopt);1823void printDIFlags(StringRef Name, DINode::DIFlags Flags);1824void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);1825template <class IntTy, class Stringifier>1826void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,1827bool ShouldSkipZero = true);1828void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);1829void printNameTableKind(StringRef Name,1830DICompileUnit::DebugNameTableKind NTK);1831};18321833} // end anonymous namespace18341835void MDFieldPrinter::printTag(const DINode *N) {1836Out << FS << "tag: ";1837auto Tag = dwarf::TagString(N->getTag());1838if (!Tag.empty())1839Out << Tag;1840else1841Out << N->getTag();1842}18431844void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {1845Out << FS << "type: ";1846auto Type = dwarf::MacinfoString(N->getMacinfoType());1847if (!Type.empty())1848Out << Type;1849else1850Out << N->getMacinfoType();1851}18521853void MDFieldPrinter::printChecksum(1854const DIFile::ChecksumInfo<StringRef> &Checksum) {1855Out << FS << "checksumkind: " << Checksum.getKindAsString();1856printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);1857}18581859void MDFieldPrinter::printString(StringRef Name, StringRef Value,1860bool ShouldSkipEmpty) {1861if (ShouldSkipEmpty && Value.empty())1862return;18631864Out << FS << Name << ": \"";1865printEscapedString(Value, Out);1866Out << "\"";1867}18681869static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,1870AsmWriterContext &WriterCtx) {1871if (!MD) {1872Out << "null";1873return;1874}1875WriteAsOperandInternal(Out, MD, WriterCtx);1876WriterCtx.onWriteMetadataAsOperand(MD);1877}18781879void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,1880bool ShouldSkipNull) {1881if (ShouldSkipNull && !MD)1882return;18831884Out << FS << Name << ": ";1885writeMetadataAsOperand(Out, MD, WriterCtx);1886}18871888template <class IntTy>1889void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {1890if (ShouldSkipZero && !Int)1891return;18921893Out << FS << Name << ": " << Int;1894}18951896void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,1897bool IsUnsigned, bool ShouldSkipZero) {1898if (ShouldSkipZero && Int.isZero())1899return;19001901Out << FS << Name << ": ";1902Int.print(Out, !IsUnsigned);1903}19041905void MDFieldPrinter::printBool(StringRef Name, bool Value,1906std::optional<bool> Default) {1907if (Default && Value == *Default)1908return;1909Out << FS << Name << ": " << (Value ? "true" : "false");1910}19111912void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {1913if (!Flags)1914return;19151916Out << FS << Name << ": ";19171918SmallVector<DINode::DIFlags, 8> SplitFlags;1919auto Extra = DINode::splitFlags(Flags, SplitFlags);19201921FieldSeparator FlagsFS(" | ");1922for (auto F : SplitFlags) {1923auto StringF = DINode::getFlagString(F);1924assert(!StringF.empty() && "Expected valid flag");1925Out << FlagsFS << StringF;1926}1927if (Extra || SplitFlags.empty())1928Out << FlagsFS << Extra;1929}19301931void MDFieldPrinter::printDISPFlags(StringRef Name,1932DISubprogram::DISPFlags Flags) {1933// Always print this field, because no flags in the IR at all will be1934// interpreted as old-style isDefinition: true.1935Out << FS << Name << ": ";19361937if (!Flags) {1938Out << 0;1939return;1940}19411942SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;1943auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);19441945FieldSeparator FlagsFS(" | ");1946for (auto F : SplitFlags) {1947auto StringF = DISubprogram::getFlagString(F);1948assert(!StringF.empty() && "Expected valid flag");1949Out << FlagsFS << StringF;1950}1951if (Extra || SplitFlags.empty())1952Out << FlagsFS << Extra;1953}19541955void MDFieldPrinter::printEmissionKind(StringRef Name,1956DICompileUnit::DebugEmissionKind EK) {1957Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);1958}19591960void MDFieldPrinter::printNameTableKind(StringRef Name,1961DICompileUnit::DebugNameTableKind NTK) {1962if (NTK == DICompileUnit::DebugNameTableKind::Default)1963return;1964Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);1965}19661967template <class IntTy, class Stringifier>1968void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,1969Stringifier toString, bool ShouldSkipZero) {1970if (!Value)1971return;19721973Out << FS << Name << ": ";1974auto S = toString(Value);1975if (!S.empty())1976Out << S;1977else1978Out << Value;1979}19801981static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,1982AsmWriterContext &WriterCtx) {1983Out << "!GenericDINode(";1984MDFieldPrinter Printer(Out, WriterCtx);1985Printer.printTag(N);1986Printer.printString("header", N->getHeader());1987if (N->getNumDwarfOperands()) {1988Out << Printer.FS << "operands: {";1989FieldSeparator IFS;1990for (auto &I : N->dwarf_operands()) {1991Out << IFS;1992writeMetadataAsOperand(Out, I, WriterCtx);1993}1994Out << "}";1995}1996Out << ")";1997}19981999static void writeDILocation(raw_ostream &Out, const DILocation *DL,2000AsmWriterContext &WriterCtx) {2001Out << "!DILocation(";2002MDFieldPrinter Printer(Out, WriterCtx);2003// Always output the line, since 0 is a relevant and important value for it.2004Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);2005Printer.printInt("column", DL->getColumn());2006Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);2007Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());2008Printer.printBool("isImplicitCode", DL->isImplicitCode(),2009/* Default */ false);2010Out << ")";2011}20122013static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,2014AsmWriterContext &WriterCtx) {2015Out << "!DIAssignID()";2016MDFieldPrinter Printer(Out, WriterCtx);2017}20182019static void writeDISubrange(raw_ostream &Out, const DISubrange *N,2020AsmWriterContext &WriterCtx) {2021Out << "!DISubrange(";2022MDFieldPrinter Printer(Out, WriterCtx);20232024auto *Count = N->getRawCountNode();2025if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {2026auto *CV = cast<ConstantInt>(CE->getValue());2027Printer.printInt("count", CV->getSExtValue(),2028/* ShouldSkipZero */ false);2029} else2030Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);20312032// A lowerBound of constant 0 should not be skipped, since it is different2033// from an unspecified lower bound (= nullptr).2034auto *LBound = N->getRawLowerBound();2035if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {2036auto *LV = cast<ConstantInt>(LE->getValue());2037Printer.printInt("lowerBound", LV->getSExtValue(),2038/* ShouldSkipZero */ false);2039} else2040Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);20412042auto *UBound = N->getRawUpperBound();2043if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {2044auto *UV = cast<ConstantInt>(UE->getValue());2045Printer.printInt("upperBound", UV->getSExtValue(),2046/* ShouldSkipZero */ false);2047} else2048Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);20492050auto *Stride = N->getRawStride();2051if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {2052auto *SV = cast<ConstantInt>(SE->getValue());2053Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);2054} else2055Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);20562057Out << ")";2058}20592060static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,2061AsmWriterContext &WriterCtx) {2062Out << "!DIGenericSubrange(";2063MDFieldPrinter Printer(Out, WriterCtx);20642065auto IsConstant = [&](Metadata *Bound) -> bool {2066if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {2067return BE->isConstant() &&2068DIExpression::SignedOrUnsignedConstant::SignedConstant ==2069*BE->isConstant();2070}2071return false;2072};20732074auto GetConstant = [&](Metadata *Bound) -> int64_t {2075assert(IsConstant(Bound) && "Expected constant");2076auto *BE = dyn_cast_or_null<DIExpression>(Bound);2077return static_cast<int64_t>(BE->getElement(1));2078};20792080auto *Count = N->getRawCountNode();2081if (IsConstant(Count))2082Printer.printInt("count", GetConstant(Count),2083/* ShouldSkipZero */ false);2084else2085Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);20862087auto *LBound = N->getRawLowerBound();2088if (IsConstant(LBound))2089Printer.printInt("lowerBound", GetConstant(LBound),2090/* ShouldSkipZero */ false);2091else2092Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);20932094auto *UBound = N->getRawUpperBound();2095if (IsConstant(UBound))2096Printer.printInt("upperBound", GetConstant(UBound),2097/* ShouldSkipZero */ false);2098else2099Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);21002101auto *Stride = N->getRawStride();2102if (IsConstant(Stride))2103Printer.printInt("stride", GetConstant(Stride),2104/* ShouldSkipZero */ false);2105else2106Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);21072108Out << ")";2109}21102111static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,2112AsmWriterContext &) {2113Out << "!DIEnumerator(";2114MDFieldPrinter Printer(Out);2115Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);2116Printer.printAPInt("value", N->getValue(), N->isUnsigned(),2117/*ShouldSkipZero=*/false);2118if (N->isUnsigned())2119Printer.printBool("isUnsigned", true);2120Out << ")";2121}21222123static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,2124AsmWriterContext &) {2125Out << "!DIBasicType(";2126MDFieldPrinter Printer(Out);2127if (N->getTag() != dwarf::DW_TAG_base_type)2128Printer.printTag(N);2129Printer.printString("name", N->getName());2130Printer.printInt("size", N->getSizeInBits());2131Printer.printInt("align", N->getAlignInBits());2132Printer.printDwarfEnum("encoding", N->getEncoding(),2133dwarf::AttributeEncodingString);2134Printer.printDIFlags("flags", N->getFlags());2135Out << ")";2136}21372138static void writeDIStringType(raw_ostream &Out, const DIStringType *N,2139AsmWriterContext &WriterCtx) {2140Out << "!DIStringType(";2141MDFieldPrinter Printer(Out, WriterCtx);2142if (N->getTag() != dwarf::DW_TAG_string_type)2143Printer.printTag(N);2144Printer.printString("name", N->getName());2145Printer.printMetadata("stringLength", N->getRawStringLength());2146Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());2147Printer.printMetadata("stringLocationExpression",2148N->getRawStringLocationExp());2149Printer.printInt("size", N->getSizeInBits());2150Printer.printInt("align", N->getAlignInBits());2151Printer.printDwarfEnum("encoding", N->getEncoding(),2152dwarf::AttributeEncodingString);2153Out << ")";2154}21552156static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,2157AsmWriterContext &WriterCtx) {2158Out << "!DIDerivedType(";2159MDFieldPrinter Printer(Out, WriterCtx);2160Printer.printTag(N);2161Printer.printString("name", N->getName());2162Printer.printMetadata("scope", N->getRawScope());2163Printer.printMetadata("file", N->getRawFile());2164Printer.printInt("line", N->getLine());2165Printer.printMetadata("baseType", N->getRawBaseType(),2166/* ShouldSkipNull */ false);2167Printer.printInt("size", N->getSizeInBits());2168Printer.printInt("align", N->getAlignInBits());2169Printer.printInt("offset", N->getOffsetInBits());2170Printer.printDIFlags("flags", N->getFlags());2171Printer.printMetadata("extraData", N->getRawExtraData());2172if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())2173Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,2174/* ShouldSkipZero */ false);2175Printer.printMetadata("annotations", N->getRawAnnotations());2176if (auto PtrAuthData = N->getPtrAuthData()) {2177Printer.printInt("ptrAuthKey", PtrAuthData->key());2178Printer.printBool("ptrAuthIsAddressDiscriminated",2179PtrAuthData->isAddressDiscriminated());2180Printer.printInt("ptrAuthExtraDiscriminator",2181PtrAuthData->extraDiscriminator());2182Printer.printBool("ptrAuthIsaPointer", PtrAuthData->isaPointer());2183Printer.printBool("ptrAuthAuthenticatesNullValues",2184PtrAuthData->authenticatesNullValues());2185}2186Out << ")";2187}21882189static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,2190AsmWriterContext &WriterCtx) {2191Out << "!DICompositeType(";2192MDFieldPrinter Printer(Out, WriterCtx);2193Printer.printTag(N);2194Printer.printString("name", N->getName());2195Printer.printMetadata("scope", N->getRawScope());2196Printer.printMetadata("file", N->getRawFile());2197Printer.printInt("line", N->getLine());2198Printer.printMetadata("baseType", N->getRawBaseType());2199Printer.printInt("size", N->getSizeInBits());2200Printer.printInt("align", N->getAlignInBits());2201Printer.printInt("offset", N->getOffsetInBits());2202Printer.printDIFlags("flags", N->getFlags());2203Printer.printMetadata("elements", N->getRawElements());2204Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),2205dwarf::LanguageString);2206Printer.printMetadata("vtableHolder", N->getRawVTableHolder());2207Printer.printMetadata("templateParams", N->getRawTemplateParams());2208Printer.printString("identifier", N->getIdentifier());2209Printer.printMetadata("discriminator", N->getRawDiscriminator());2210Printer.printMetadata("dataLocation", N->getRawDataLocation());2211Printer.printMetadata("associated", N->getRawAssociated());2212Printer.printMetadata("allocated", N->getRawAllocated());2213if (auto *RankConst = N->getRankConst())2214Printer.printInt("rank", RankConst->getSExtValue(),2215/* ShouldSkipZero */ false);2216else2217Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);2218Printer.printMetadata("annotations", N->getRawAnnotations());2219Out << ")";2220}22212222static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,2223AsmWriterContext &WriterCtx) {2224Out << "!DISubroutineType(";2225MDFieldPrinter Printer(Out, WriterCtx);2226Printer.printDIFlags("flags", N->getFlags());2227Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);2228Printer.printMetadata("types", N->getRawTypeArray(),2229/* ShouldSkipNull */ false);2230Out << ")";2231}22322233static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {2234Out << "!DIFile(";2235MDFieldPrinter Printer(Out);2236Printer.printString("filename", N->getFilename(),2237/* ShouldSkipEmpty */ false);2238Printer.printString("directory", N->getDirectory(),2239/* ShouldSkipEmpty */ false);2240// Print all values for checksum together, or not at all.2241if (N->getChecksum())2242Printer.printChecksum(*N->getChecksum());2243Printer.printString("source", N->getSource().value_or(StringRef()),2244/* ShouldSkipEmpty */ true);2245Out << ")";2246}22472248static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,2249AsmWriterContext &WriterCtx) {2250Out << "!DICompileUnit(";2251MDFieldPrinter Printer(Out, WriterCtx);2252Printer.printDwarfEnum("language", N->getSourceLanguage(),2253dwarf::LanguageString, /* ShouldSkipZero */ false);2254Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);2255Printer.printString("producer", N->getProducer());2256Printer.printBool("isOptimized", N->isOptimized());2257Printer.printString("flags", N->getFlags());2258Printer.printInt("runtimeVersion", N->getRuntimeVersion(),2259/* ShouldSkipZero */ false);2260Printer.printString("splitDebugFilename", N->getSplitDebugFilename());2261Printer.printEmissionKind("emissionKind", N->getEmissionKind());2262Printer.printMetadata("enums", N->getRawEnumTypes());2263Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());2264Printer.printMetadata("globals", N->getRawGlobalVariables());2265Printer.printMetadata("imports", N->getRawImportedEntities());2266Printer.printMetadata("macros", N->getRawMacros());2267Printer.printInt("dwoId", N->getDWOId());2268Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);2269Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),2270false);2271Printer.printNameTableKind("nameTableKind", N->getNameTableKind());2272Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);2273Printer.printString("sysroot", N->getSysRoot());2274Printer.printString("sdk", N->getSDK());2275Out << ")";2276}22772278static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,2279AsmWriterContext &WriterCtx) {2280Out << "!DISubprogram(";2281MDFieldPrinter Printer(Out, WriterCtx);2282Printer.printString("name", N->getName());2283Printer.printString("linkageName", N->getLinkageName());2284Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2285Printer.printMetadata("file", N->getRawFile());2286Printer.printInt("line", N->getLine());2287Printer.printMetadata("type", N->getRawType());2288Printer.printInt("scopeLine", N->getScopeLine());2289Printer.printMetadata("containingType", N->getRawContainingType());2290if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||2291N->getVirtualIndex() != 0)2292Printer.printInt("virtualIndex", N->getVirtualIndex(), false);2293Printer.printInt("thisAdjustment", N->getThisAdjustment());2294Printer.printDIFlags("flags", N->getFlags());2295Printer.printDISPFlags("spFlags", N->getSPFlags());2296Printer.printMetadata("unit", N->getRawUnit());2297Printer.printMetadata("templateParams", N->getRawTemplateParams());2298Printer.printMetadata("declaration", N->getRawDeclaration());2299Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());2300Printer.printMetadata("thrownTypes", N->getRawThrownTypes());2301Printer.printMetadata("annotations", N->getRawAnnotations());2302Printer.printString("targetFuncName", N->getTargetFuncName());2303Out << ")";2304}23052306static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,2307AsmWriterContext &WriterCtx) {2308Out << "!DILexicalBlock(";2309MDFieldPrinter Printer(Out, WriterCtx);2310Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2311Printer.printMetadata("file", N->getRawFile());2312Printer.printInt("line", N->getLine());2313Printer.printInt("column", N->getColumn());2314Out << ")";2315}23162317static void writeDILexicalBlockFile(raw_ostream &Out,2318const DILexicalBlockFile *N,2319AsmWriterContext &WriterCtx) {2320Out << "!DILexicalBlockFile(";2321MDFieldPrinter Printer(Out, WriterCtx);2322Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2323Printer.printMetadata("file", N->getRawFile());2324Printer.printInt("discriminator", N->getDiscriminator(),2325/* ShouldSkipZero */ false);2326Out << ")";2327}23282329static void writeDINamespace(raw_ostream &Out, const DINamespace *N,2330AsmWriterContext &WriterCtx) {2331Out << "!DINamespace(";2332MDFieldPrinter Printer(Out, WriterCtx);2333Printer.printString("name", N->getName());2334Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2335Printer.printBool("exportSymbols", N->getExportSymbols(), false);2336Out << ")";2337}23382339static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,2340AsmWriterContext &WriterCtx) {2341Out << "!DICommonBlock(";2342MDFieldPrinter Printer(Out, WriterCtx);2343Printer.printMetadata("scope", N->getRawScope(), false);2344Printer.printMetadata("declaration", N->getRawDecl(), false);2345Printer.printString("name", N->getName());2346Printer.printMetadata("file", N->getRawFile());2347Printer.printInt("line", N->getLineNo());2348Out << ")";2349}23502351static void writeDIMacro(raw_ostream &Out, const DIMacro *N,2352AsmWriterContext &WriterCtx) {2353Out << "!DIMacro(";2354MDFieldPrinter Printer(Out, WriterCtx);2355Printer.printMacinfoType(N);2356Printer.printInt("line", N->getLine());2357Printer.printString("name", N->getName());2358Printer.printString("value", N->getValue());2359Out << ")";2360}23612362static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,2363AsmWriterContext &WriterCtx) {2364Out << "!DIMacroFile(";2365MDFieldPrinter Printer(Out, WriterCtx);2366Printer.printInt("line", N->getLine());2367Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);2368Printer.printMetadata("nodes", N->getRawElements());2369Out << ")";2370}23712372static void writeDIModule(raw_ostream &Out, const DIModule *N,2373AsmWriterContext &WriterCtx) {2374Out << "!DIModule(";2375MDFieldPrinter Printer(Out, WriterCtx);2376Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2377Printer.printString("name", N->getName());2378Printer.printString("configMacros", N->getConfigurationMacros());2379Printer.printString("includePath", N->getIncludePath());2380Printer.printString("apinotes", N->getAPINotesFile());2381Printer.printMetadata("file", N->getRawFile());2382Printer.printInt("line", N->getLineNo());2383Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);2384Out << ")";2385}23862387static void writeDITemplateTypeParameter(raw_ostream &Out,2388const DITemplateTypeParameter *N,2389AsmWriterContext &WriterCtx) {2390Out << "!DITemplateTypeParameter(";2391MDFieldPrinter Printer(Out, WriterCtx);2392Printer.printString("name", N->getName());2393Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);2394Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);2395Out << ")";2396}23972398static void writeDITemplateValueParameter(raw_ostream &Out,2399const DITemplateValueParameter *N,2400AsmWriterContext &WriterCtx) {2401Out << "!DITemplateValueParameter(";2402MDFieldPrinter Printer(Out, WriterCtx);2403if (N->getTag() != dwarf::DW_TAG_template_value_parameter)2404Printer.printTag(N);2405Printer.printString("name", N->getName());2406Printer.printMetadata("type", N->getRawType());2407Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);2408Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);2409Out << ")";2410}24112412static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,2413AsmWriterContext &WriterCtx) {2414Out << "!DIGlobalVariable(";2415MDFieldPrinter Printer(Out, WriterCtx);2416Printer.printString("name", N->getName());2417Printer.printString("linkageName", N->getLinkageName());2418Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2419Printer.printMetadata("file", N->getRawFile());2420Printer.printInt("line", N->getLine());2421Printer.printMetadata("type", N->getRawType());2422Printer.printBool("isLocal", N->isLocalToUnit());2423Printer.printBool("isDefinition", N->isDefinition());2424Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());2425Printer.printMetadata("templateParams", N->getRawTemplateParams());2426Printer.printInt("align", N->getAlignInBits());2427Printer.printMetadata("annotations", N->getRawAnnotations());2428Out << ")";2429}24302431static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,2432AsmWriterContext &WriterCtx) {2433Out << "!DILocalVariable(";2434MDFieldPrinter Printer(Out, WriterCtx);2435Printer.printString("name", N->getName());2436Printer.printInt("arg", N->getArg());2437Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2438Printer.printMetadata("file", N->getRawFile());2439Printer.printInt("line", N->getLine());2440Printer.printMetadata("type", N->getRawType());2441Printer.printDIFlags("flags", N->getFlags());2442Printer.printInt("align", N->getAlignInBits());2443Printer.printMetadata("annotations", N->getRawAnnotations());2444Out << ")";2445}24462447static void writeDILabel(raw_ostream &Out, const DILabel *N,2448AsmWriterContext &WriterCtx) {2449Out << "!DILabel(";2450MDFieldPrinter Printer(Out, WriterCtx);2451Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2452Printer.printString("name", N->getName());2453Printer.printMetadata("file", N->getRawFile());2454Printer.printInt("line", N->getLine());2455Out << ")";2456}24572458static void writeDIExpression(raw_ostream &Out, const DIExpression *N,2459AsmWriterContext &WriterCtx) {2460Out << "!DIExpression(";2461FieldSeparator FS;2462if (N->isValid()) {2463for (const DIExpression::ExprOperand &Op : N->expr_ops()) {2464auto OpStr = dwarf::OperationEncodingString(Op.getOp());2465assert(!OpStr.empty() && "Expected valid opcode");24662467Out << FS << OpStr;2468if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {2469Out << FS << Op.getArg(0);2470Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));2471} else {2472for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)2473Out << FS << Op.getArg(A);2474}2475}2476} else {2477for (const auto &I : N->getElements())2478Out << FS << I;2479}2480Out << ")";2481}24822483static void writeDIArgList(raw_ostream &Out, const DIArgList *N,2484AsmWriterContext &WriterCtx,2485bool FromValue = false) {2486assert(FromValue &&2487"Unexpected DIArgList metadata outside of value argument");2488Out << "!DIArgList(";2489FieldSeparator FS;2490MDFieldPrinter Printer(Out, WriterCtx);2491for (Metadata *Arg : N->getArgs()) {2492Out << FS;2493WriteAsOperandInternal(Out, Arg, WriterCtx, true);2494}2495Out << ")";2496}24972498static void writeDIGlobalVariableExpression(raw_ostream &Out,2499const DIGlobalVariableExpression *N,2500AsmWriterContext &WriterCtx) {2501Out << "!DIGlobalVariableExpression(";2502MDFieldPrinter Printer(Out, WriterCtx);2503Printer.printMetadata("var", N->getVariable());2504Printer.printMetadata("expr", N->getExpression());2505Out << ")";2506}25072508static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,2509AsmWriterContext &WriterCtx) {2510Out << "!DIObjCProperty(";2511MDFieldPrinter Printer(Out, WriterCtx);2512Printer.printString("name", N->getName());2513Printer.printMetadata("file", N->getRawFile());2514Printer.printInt("line", N->getLine());2515Printer.printString("setter", N->getSetterName());2516Printer.printString("getter", N->getGetterName());2517Printer.printInt("attributes", N->getAttributes());2518Printer.printMetadata("type", N->getRawType());2519Out << ")";2520}25212522static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,2523AsmWriterContext &WriterCtx) {2524Out << "!DIImportedEntity(";2525MDFieldPrinter Printer(Out, WriterCtx);2526Printer.printTag(N);2527Printer.printString("name", N->getName());2528Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);2529Printer.printMetadata("entity", N->getRawEntity());2530Printer.printMetadata("file", N->getRawFile());2531Printer.printInt("line", N->getLine());2532Printer.printMetadata("elements", N->getRawElements());2533Out << ")";2534}25352536static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,2537AsmWriterContext &Ctx) {2538if (Node->isDistinct())2539Out << "distinct ";2540else if (Node->isTemporary())2541Out << "<temporary!> "; // Handle broken code.25422543switch (Node->getMetadataID()) {2544default:2545llvm_unreachable("Expected uniquable MDNode");2546#define HANDLE_MDNODE_LEAF(CLASS) \2547case Metadata::CLASS##Kind: \2548write##CLASS(Out, cast<CLASS>(Node), Ctx); \2549break;2550#include "llvm/IR/Metadata.def"2551}2552}25532554// Full implementation of printing a Value as an operand with support for2555// TypePrinting, etc.2556static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,2557AsmWriterContext &WriterCtx) {2558if (V->hasName()) {2559PrintLLVMName(Out, V);2560return;2561}25622563const Constant *CV = dyn_cast<Constant>(V);2564if (CV && !isa<GlobalValue>(CV)) {2565assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");2566WriteConstantInternal(Out, CV, WriterCtx);2567return;2568}25692570if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {2571Out << "asm ";2572if (IA->hasSideEffects())2573Out << "sideeffect ";2574if (IA->isAlignStack())2575Out << "alignstack ";2576// We don't emit the AD_ATT dialect as it's the assumed default.2577if (IA->getDialect() == InlineAsm::AD_Intel)2578Out << "inteldialect ";2579if (IA->canThrow())2580Out << "unwind ";2581Out << '"';2582printEscapedString(IA->getAsmString(), Out);2583Out << "\", \"";2584printEscapedString(IA->getConstraintString(), Out);2585Out << '"';2586return;2587}25882589if (auto *MD = dyn_cast<MetadataAsValue>(V)) {2590WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,2591/* FromValue */ true);2592return;2593}25942595char Prefix = '%';2596int Slot;2597auto *Machine = WriterCtx.Machine;2598// If we have a SlotTracker, use it.2599if (Machine) {2600if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {2601Slot = Machine->getGlobalSlot(GV);2602Prefix = '@';2603} else {2604Slot = Machine->getLocalSlot(V);26052606// If the local value didn't succeed, then we may be referring to a value2607// from a different function. Translate it, as this can happen when using2608// address of blocks.2609if (Slot == -1)2610if ((Machine = createSlotTracker(V))) {2611Slot = Machine->getLocalSlot(V);2612delete Machine;2613}2614}2615} else if ((Machine = createSlotTracker(V))) {2616// Otherwise, create one to get the # and then destroy it.2617if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {2618Slot = Machine->getGlobalSlot(GV);2619Prefix = '@';2620} else {2621Slot = Machine->getLocalSlot(V);2622}2623delete Machine;2624Machine = nullptr;2625} else {2626Slot = -1;2627}26282629if (Slot != -1)2630Out << Prefix << Slot;2631else2632Out << "<badref>";2633}26342635static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,2636AsmWriterContext &WriterCtx,2637bool FromValue) {2638// Write DIExpressions and DIArgLists inline when used as a value. Improves2639// readability of debug info intrinsics.2640if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {2641writeDIExpression(Out, Expr, WriterCtx);2642return;2643}2644if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {2645writeDIArgList(Out, ArgList, WriterCtx, FromValue);2646return;2647}26482649if (const MDNode *N = dyn_cast<MDNode>(MD)) {2650std::unique_ptr<SlotTracker> MachineStorage;2651SaveAndRestore SARMachine(WriterCtx.Machine);2652if (!WriterCtx.Machine) {2653MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);2654WriterCtx.Machine = MachineStorage.get();2655}2656int Slot = WriterCtx.Machine->getMetadataSlot(N);2657if (Slot == -1) {2658if (const DILocation *Loc = dyn_cast<DILocation>(N)) {2659writeDILocation(Out, Loc, WriterCtx);2660return;2661}2662// Give the pointer value instead of "badref", since this comes up all2663// the time when debugging.2664Out << "<" << N << ">";2665} else2666Out << '!' << Slot;2667return;2668}26692670if (const MDString *MDS = dyn_cast<MDString>(MD)) {2671Out << "!\"";2672printEscapedString(MDS->getString(), Out);2673Out << '"';2674return;2675}26762677auto *V = cast<ValueAsMetadata>(MD);2678assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");2679assert((FromValue || !isa<LocalAsMetadata>(V)) &&2680"Unexpected function-local metadata outside of value argument");26812682WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);2683Out << ' ';2684WriteAsOperandInternal(Out, V->getValue(), WriterCtx);2685}26862687namespace {26882689class AssemblyWriter {2690formatted_raw_ostream &Out;2691const Module *TheModule = nullptr;2692const ModuleSummaryIndex *TheIndex = nullptr;2693std::unique_ptr<SlotTracker> SlotTrackerStorage;2694SlotTracker &Machine;2695TypePrinting TypePrinter;2696AssemblyAnnotationWriter *AnnotationWriter = nullptr;2697SetVector<const Comdat *> Comdats;2698bool IsForDebug;2699bool ShouldPreserveUseListOrder;2700UseListOrderMap UseListOrders;2701SmallVector<StringRef, 8> MDNames;2702/// Synchronization scope names registered with LLVMContext.2703SmallVector<StringRef, 8> SSNs;2704DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;27052706public:2707/// Construct an AssemblyWriter with an external SlotTracker2708AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,2709AssemblyAnnotationWriter *AAW, bool IsForDebug,2710bool ShouldPreserveUseListOrder = false);27112712AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,2713const ModuleSummaryIndex *Index, bool IsForDebug);27142715AsmWriterContext getContext() {2716return AsmWriterContext(&TypePrinter, &Machine, TheModule);2717}27182719void printMDNodeBody(const MDNode *MD);2720void printNamedMDNode(const NamedMDNode *NMD);27212722void printModule(const Module *M);27232724void writeOperand(const Value *Op, bool PrintType);2725void writeParamOperand(const Value *Operand, AttributeSet Attrs);2726void writeOperandBundles(const CallBase *Call);2727void writeSyncScope(const LLVMContext &Context,2728SyncScope::ID SSID);2729void writeAtomic(const LLVMContext &Context,2730AtomicOrdering Ordering,2731SyncScope::ID SSID);2732void writeAtomicCmpXchg(const LLVMContext &Context,2733AtomicOrdering SuccessOrdering,2734AtomicOrdering FailureOrdering,2735SyncScope::ID SSID);27362737void writeAllMDNodes();2738void writeMDNode(unsigned Slot, const MDNode *Node);2739void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);2740void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);2741void writeAllAttributeGroups();27422743void printTypeIdentities();2744void printGlobal(const GlobalVariable *GV);2745void printAlias(const GlobalAlias *GA);2746void printIFunc(const GlobalIFunc *GI);2747void printComdat(const Comdat *C);2748void printFunction(const Function *F);2749void printArgument(const Argument *FA, AttributeSet Attrs);2750void printBasicBlock(const BasicBlock *BB);2751void printInstructionLine(const Instruction &I);2752void printInstruction(const Instruction &I);2753void printDbgMarker(const DbgMarker &DPI);2754void printDbgVariableRecord(const DbgVariableRecord &DVR);2755void printDbgLabelRecord(const DbgLabelRecord &DLR);2756void printDbgRecord(const DbgRecord &DR);2757void printDbgRecordLine(const DbgRecord &DR);27582759void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);2760void printUseLists(const Function *F);27612762void printModuleSummaryIndex();2763void printSummaryInfo(unsigned Slot, const ValueInfo &VI);2764void printSummary(const GlobalValueSummary &Summary);2765void printAliasSummary(const AliasSummary *AS);2766void printGlobalVarSummary(const GlobalVarSummary *GS);2767void printFunctionSummary(const FunctionSummary *FS);2768void printTypeIdSummary(const TypeIdSummary &TIS);2769void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);2770void printTypeTestResolution(const TypeTestResolution &TTRes);2771void printArgs(const std::vector<uint64_t> &Args);2772void printWPDRes(const WholeProgramDevirtResolution &WPDRes);2773void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);2774void printVFuncId(const FunctionSummary::VFuncId VFId);2775void2776printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,2777const char *Tag);2778void2779printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,2780const char *Tag);27812782private:2783/// Print out metadata attachments.2784void printMetadataAttachments(2785const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,2786StringRef Separator);27872788// printInfoComment - Print a little comment after the instruction indicating2789// which slot it occupies.2790void printInfoComment(const Value &V);27912792// printGCRelocateComment - print comment after call to the gc.relocate2793// intrinsic indicating base and derived pointer names.2794void printGCRelocateComment(const GCRelocateInst &Relocate);2795};27962797} // end anonymous namespace27982799AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,2800const Module *M, AssemblyAnnotationWriter *AAW,2801bool IsForDebug, bool ShouldPreserveUseListOrder)2802: Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),2803IsForDebug(IsForDebug),2804ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {2805if (!TheModule)2806return;2807for (const GlobalObject &GO : TheModule->global_objects())2808if (const Comdat *C = GO.getComdat())2809Comdats.insert(C);2810}28112812AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,2813const ModuleSummaryIndex *Index, bool IsForDebug)2814: Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),2815IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}28162817void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {2818if (!Operand) {2819Out << "<null operand!>";2820return;2821}2822if (PrintType) {2823TypePrinter.print(Operand->getType(), Out);2824Out << ' ';2825}2826auto WriterCtx = getContext();2827WriteAsOperandInternal(Out, Operand, WriterCtx);2828}28292830void AssemblyWriter::writeSyncScope(const LLVMContext &Context,2831SyncScope::ID SSID) {2832switch (SSID) {2833case SyncScope::System: {2834break;2835}2836default: {2837if (SSNs.empty())2838Context.getSyncScopeNames(SSNs);28392840Out << " syncscope(\"";2841printEscapedString(SSNs[SSID], Out);2842Out << "\")";2843break;2844}2845}2846}28472848void AssemblyWriter::writeAtomic(const LLVMContext &Context,2849AtomicOrdering Ordering,2850SyncScope::ID SSID) {2851if (Ordering == AtomicOrdering::NotAtomic)2852return;28532854writeSyncScope(Context, SSID);2855Out << " " << toIRString(Ordering);2856}28572858void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,2859AtomicOrdering SuccessOrdering,2860AtomicOrdering FailureOrdering,2861SyncScope::ID SSID) {2862assert(SuccessOrdering != AtomicOrdering::NotAtomic &&2863FailureOrdering != AtomicOrdering::NotAtomic);28642865writeSyncScope(Context, SSID);2866Out << " " << toIRString(SuccessOrdering);2867Out << " " << toIRString(FailureOrdering);2868}28692870void AssemblyWriter::writeParamOperand(const Value *Operand,2871AttributeSet Attrs) {2872if (!Operand) {2873Out << "<null operand!>";2874return;2875}28762877// Print the type2878TypePrinter.print(Operand->getType(), Out);2879// Print parameter attributes list2880if (Attrs.hasAttributes()) {2881Out << ' ';2882writeAttributeSet(Attrs);2883}2884Out << ' ';2885// Print the operand2886auto WriterCtx = getContext();2887WriteAsOperandInternal(Out, Operand, WriterCtx);2888}28892890void AssemblyWriter::writeOperandBundles(const CallBase *Call) {2891if (!Call->hasOperandBundles())2892return;28932894Out << " [ ";28952896bool FirstBundle = true;2897for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {2898OperandBundleUse BU = Call->getOperandBundleAt(i);28992900if (!FirstBundle)2901Out << ", ";2902FirstBundle = false;29032904Out << '"';2905printEscapedString(BU.getTagName(), Out);2906Out << '"';29072908Out << '(';29092910bool FirstInput = true;2911auto WriterCtx = getContext();2912for (const auto &Input : BU.Inputs) {2913if (!FirstInput)2914Out << ", ";2915FirstInput = false;29162917if (Input == nullptr)2918Out << "<null operand bundle!>";2919else {2920TypePrinter.print(Input->getType(), Out);2921Out << " ";2922WriteAsOperandInternal(Out, Input, WriterCtx);2923}2924}29252926Out << ')';2927}29282929Out << " ]";2930}29312932void AssemblyWriter::printModule(const Module *M) {2933Machine.initializeIfNeeded();29342935if (ShouldPreserveUseListOrder)2936UseListOrders = predictUseListOrder(M);29372938if (!M->getModuleIdentifier().empty() &&2939// Don't print the ID if it will start a new line (which would2940// require a comment char before it).2941M->getModuleIdentifier().find('\n') == std::string::npos)2942Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";29432944if (!M->getSourceFileName().empty()) {2945Out << "source_filename = \"";2946printEscapedString(M->getSourceFileName(), Out);2947Out << "\"\n";2948}29492950const std::string &DL = M->getDataLayoutStr();2951if (!DL.empty())2952Out << "target datalayout = \"" << DL << "\"\n";2953if (!M->getTargetTriple().empty())2954Out << "target triple = \"" << M->getTargetTriple() << "\"\n";29552956if (!M->getModuleInlineAsm().empty()) {2957Out << '\n';29582959// Split the string into lines, to make it easier to read the .ll file.2960StringRef Asm = M->getModuleInlineAsm();2961do {2962StringRef Front;2963std::tie(Front, Asm) = Asm.split('\n');29642965// We found a newline, print the portion of the asm string from the2966// last newline up to this newline.2967Out << "module asm \"";2968printEscapedString(Front, Out);2969Out << "\"\n";2970} while (!Asm.empty());2971}29722973printTypeIdentities();29742975// Output all comdats.2976if (!Comdats.empty())2977Out << '\n';2978for (const Comdat *C : Comdats) {2979printComdat(C);2980if (C != Comdats.back())2981Out << '\n';2982}29832984// Output all globals.2985if (!M->global_empty()) Out << '\n';2986for (const GlobalVariable &GV : M->globals()) {2987printGlobal(&GV); Out << '\n';2988}29892990// Output all aliases.2991if (!M->alias_empty()) Out << "\n";2992for (const GlobalAlias &GA : M->aliases())2993printAlias(&GA);29942995// Output all ifuncs.2996if (!M->ifunc_empty()) Out << "\n";2997for (const GlobalIFunc &GI : M->ifuncs())2998printIFunc(&GI);29993000// Output all of the functions.3001for (const Function &F : *M) {3002Out << '\n';3003printFunction(&F);3004}30053006// Output global use-lists.3007printUseLists(nullptr);30083009// Output all attribute groups.3010if (!Machine.as_empty()) {3011Out << '\n';3012writeAllAttributeGroups();3013}30143015// Output named metadata.3016if (!M->named_metadata_empty()) Out << '\n';30173018for (const NamedMDNode &Node : M->named_metadata())3019printNamedMDNode(&Node);30203021// Output metadata.3022if (!Machine.mdn_empty()) {3023Out << '\n';3024writeAllMDNodes();3025}3026}30273028void AssemblyWriter::printModuleSummaryIndex() {3029assert(TheIndex);3030int NumSlots = Machine.initializeIndexIfNeeded();30313032Out << "\n";30333034// Print module path entries. To print in order, add paths to a vector3035// indexed by module slot.3036std::vector<std::pair<std::string, ModuleHash>> moduleVec;3037std::string RegularLTOModuleName =3038ModuleSummaryIndex::getRegularLTOModuleName();3039moduleVec.resize(TheIndex->modulePaths().size());3040for (auto &[ModPath, ModHash] : TheIndex->modulePaths())3041moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(3042// An empty module path is a special entry for a regular LTO module3043// created during the thin link.3044ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);30453046unsigned i = 0;3047for (auto &ModPair : moduleVec) {3048Out << "^" << i++ << " = module: (";3049Out << "path: \"";3050printEscapedString(ModPair.first, Out);3051Out << "\", hash: (";3052FieldSeparator FS;3053for (auto Hash : ModPair.second)3054Out << FS << Hash;3055Out << "))\n";3056}30573058// FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer3059// for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).3060for (auto &GlobalList : *TheIndex) {3061auto GUID = GlobalList.first;3062for (auto &Summary : GlobalList.second.SummaryList)3063SummaryToGUIDMap[Summary.get()] = GUID;3064}30653066// Print the global value summary entries.3067for (auto &GlobalList : *TheIndex) {3068auto GUID = GlobalList.first;3069auto VI = TheIndex->getValueInfo(GlobalList);3070printSummaryInfo(Machine.getGUIDSlot(GUID), VI);3071}30723073// Print the TypeIdMap entries.3074for (const auto &TID : TheIndex->typeIds()) {3075Out << "^" << Machine.getTypeIdSlot(TID.second.first)3076<< " = typeid: (name: \"" << TID.second.first << "\"";3077printTypeIdSummary(TID.second.second);3078Out << ") ; guid = " << TID.first << "\n";3079}30803081// Print the TypeIdCompatibleVtableMap entries.3082for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {3083auto GUID = GlobalValue::getGUID(TId.first);3084Out << "^" << Machine.getTypeIdCompatibleVtableSlot(TId.first)3085<< " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";3086printTypeIdCompatibleVtableSummary(TId.second);3087Out << ") ; guid = " << GUID << "\n";3088}30893090// Don't emit flags when it's not really needed (value is zero by default).3091if (TheIndex->getFlags()) {3092Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";3093++NumSlots;3094}30953096Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()3097<< "\n";3098}30993100static const char *3101getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {3102switch (K) {3103case WholeProgramDevirtResolution::Indir:3104return "indir";3105case WholeProgramDevirtResolution::SingleImpl:3106return "singleImpl";3107case WholeProgramDevirtResolution::BranchFunnel:3108return "branchFunnel";3109}3110llvm_unreachable("invalid WholeProgramDevirtResolution kind");3111}31123113static const char *getWholeProgDevirtResByArgKindName(3114WholeProgramDevirtResolution::ByArg::Kind K) {3115switch (K) {3116case WholeProgramDevirtResolution::ByArg::Indir:3117return "indir";3118case WholeProgramDevirtResolution::ByArg::UniformRetVal:3119return "uniformRetVal";3120case WholeProgramDevirtResolution::ByArg::UniqueRetVal:3121return "uniqueRetVal";3122case WholeProgramDevirtResolution::ByArg::VirtualConstProp:3123return "virtualConstProp";3124}3125llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");3126}31273128static const char *getTTResKindName(TypeTestResolution::Kind K) {3129switch (K) {3130case TypeTestResolution::Unknown:3131return "unknown";3132case TypeTestResolution::Unsat:3133return "unsat";3134case TypeTestResolution::ByteArray:3135return "byteArray";3136case TypeTestResolution::Inline:3137return "inline";3138case TypeTestResolution::Single:3139return "single";3140case TypeTestResolution::AllOnes:3141return "allOnes";3142}3143llvm_unreachable("invalid TypeTestResolution kind");3144}31453146void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {3147Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)3148<< ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;31493150// The following fields are only used if the target does not support the use3151// of absolute symbols to store constants. Print only if non-zero.3152if (TTRes.AlignLog2)3153Out << ", alignLog2: " << TTRes.AlignLog2;3154if (TTRes.SizeM1)3155Out << ", sizeM1: " << TTRes.SizeM1;3156if (TTRes.BitMask)3157// BitMask is uint8_t which causes it to print the corresponding char.3158Out << ", bitMask: " << (unsigned)TTRes.BitMask;3159if (TTRes.InlineBits)3160Out << ", inlineBits: " << TTRes.InlineBits;31613162Out << ")";3163}31643165void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {3166Out << ", summary: (";3167printTypeTestResolution(TIS.TTRes);3168if (!TIS.WPDRes.empty()) {3169Out << ", wpdResolutions: (";3170FieldSeparator FS;3171for (auto &WPDRes : TIS.WPDRes) {3172Out << FS;3173Out << "(offset: " << WPDRes.first << ", ";3174printWPDRes(WPDRes.second);3175Out << ")";3176}3177Out << ")";3178}3179Out << ")";3180}31813182void AssemblyWriter::printTypeIdCompatibleVtableSummary(3183const TypeIdCompatibleVtableInfo &TI) {3184Out << ", summary: (";3185FieldSeparator FS;3186for (auto &P : TI) {3187Out << FS;3188Out << "(offset: " << P.AddressPointOffset << ", ";3189Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());3190Out << ")";3191}3192Out << ")";3193}31943195void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {3196Out << "args: (";3197FieldSeparator FS;3198for (auto arg : Args) {3199Out << FS;3200Out << arg;3201}3202Out << ")";3203}32043205void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {3206Out << "wpdRes: (kind: ";3207Out << getWholeProgDevirtResKindName(WPDRes.TheKind);32083209if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)3210Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";32113212if (!WPDRes.ResByArg.empty()) {3213Out << ", resByArg: (";3214FieldSeparator FS;3215for (auto &ResByArg : WPDRes.ResByArg) {3216Out << FS;3217printArgs(ResByArg.first);3218Out << ", byArg: (kind: ";3219Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);3220if (ResByArg.second.TheKind ==3221WholeProgramDevirtResolution::ByArg::UniformRetVal ||3222ResByArg.second.TheKind ==3223WholeProgramDevirtResolution::ByArg::UniqueRetVal)3224Out << ", info: " << ResByArg.second.Info;32253226// The following fields are only used if the target does not support the3227// use of absolute symbols to store constants. Print only if non-zero.3228if (ResByArg.second.Byte || ResByArg.second.Bit)3229Out << ", byte: " << ResByArg.second.Byte3230<< ", bit: " << ResByArg.second.Bit;32313232Out << ")";3233}3234Out << ")";3235}3236Out << ")";3237}32383239static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {3240switch (SK) {3241case GlobalValueSummary::AliasKind:3242return "alias";3243case GlobalValueSummary::FunctionKind:3244return "function";3245case GlobalValueSummary::GlobalVarKind:3246return "variable";3247}3248llvm_unreachable("invalid summary kind");3249}32503251void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {3252Out << ", aliasee: ";3253// The indexes emitted for distributed backends may not include the3254// aliasee summary (only if it is being imported directly). Handle3255// that case by just emitting "null" as the aliasee.3256if (AS->hasAliasee())3257Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);3258else3259Out << "null";3260}32613262void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {3263auto VTableFuncs = GS->vTableFuncs();3264Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "3265<< "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "3266<< "constant: " << GS->VarFlags.Constant;3267if (!VTableFuncs.empty())3268Out << ", "3269<< "vcall_visibility: " << GS->VarFlags.VCallVisibility;3270Out << ")";32713272if (!VTableFuncs.empty()) {3273Out << ", vTableFuncs: (";3274FieldSeparator FS;3275for (auto &P : VTableFuncs) {3276Out << FS;3277Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())3278<< ", offset: " << P.VTableOffset;3279Out << ")";3280}3281Out << ")";3282}3283}32843285static std::string getLinkageName(GlobalValue::LinkageTypes LT) {3286switch (LT) {3287case GlobalValue::ExternalLinkage:3288return "external";3289case GlobalValue::PrivateLinkage:3290return "private";3291case GlobalValue::InternalLinkage:3292return "internal";3293case GlobalValue::LinkOnceAnyLinkage:3294return "linkonce";3295case GlobalValue::LinkOnceODRLinkage:3296return "linkonce_odr";3297case GlobalValue::WeakAnyLinkage:3298return "weak";3299case GlobalValue::WeakODRLinkage:3300return "weak_odr";3301case GlobalValue::CommonLinkage:3302return "common";3303case GlobalValue::AppendingLinkage:3304return "appending";3305case GlobalValue::ExternalWeakLinkage:3306return "extern_weak";3307case GlobalValue::AvailableExternallyLinkage:3308return "available_externally";3309}3310llvm_unreachable("invalid linkage");3311}33123313// When printing the linkage types in IR where the ExternalLinkage is3314// not printed, and other linkage types are expected to be printed with3315// a space after the name.3316static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {3317if (LT == GlobalValue::ExternalLinkage)3318return "";3319return getLinkageName(LT) + " ";3320}33213322static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {3323switch (Vis) {3324case GlobalValue::DefaultVisibility:3325return "default";3326case GlobalValue::HiddenVisibility:3327return "hidden";3328case GlobalValue::ProtectedVisibility:3329return "protected";3330}3331llvm_unreachable("invalid visibility");3332}33333334static const char *getImportTypeName(GlobalValueSummary::ImportKind IK) {3335switch (IK) {3336case GlobalValueSummary::Definition:3337return "definition";3338case GlobalValueSummary::Declaration:3339return "declaration";3340}3341llvm_unreachable("invalid import kind");3342}33433344void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {3345Out << ", insts: " << FS->instCount();3346if (FS->fflags().anyFlagSet())3347Out << ", " << FS->fflags();33483349if (!FS->calls().empty()) {3350Out << ", calls: (";3351FieldSeparator IFS;3352for (auto &Call : FS->calls()) {3353Out << IFS;3354Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());3355if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)3356Out << ", hotness: " << getHotnessName(Call.second.getHotness());3357else if (Call.second.RelBlockFreq)3358Out << ", relbf: " << Call.second.RelBlockFreq;3359// Follow the convention of emitting flags as a boolean value, but only3360// emit if true to avoid unnecessary verbosity and test churn.3361if (Call.second.HasTailCall)3362Out << ", tail: 1";3363Out << ")";3364}3365Out << ")";3366}33673368if (const auto *TIdInfo = FS->getTypeIdInfo())3369printTypeIdInfo(*TIdInfo);33703371// The AllocationType identifiers capture the profiled context behavior3372// reaching a specific static allocation site (possibly cloned).3373auto AllocTypeName = [](uint8_t Type) -> const char * {3374switch (Type) {3375case (uint8_t)AllocationType::None:3376return "none";3377case (uint8_t)AllocationType::NotCold:3378return "notcold";3379case (uint8_t)AllocationType::Cold:3380return "cold";3381case (uint8_t)AllocationType::Hot:3382return "hot";3383}3384llvm_unreachable("Unexpected alloc type");3385};33863387if (!FS->allocs().empty()) {3388Out << ", allocs: (";3389FieldSeparator AFS;3390for (auto &AI : FS->allocs()) {3391Out << AFS;3392Out << "(versions: (";3393FieldSeparator VFS;3394for (auto V : AI.Versions) {3395Out << VFS;3396Out << AllocTypeName(V);3397}3398Out << "), memProf: (";3399FieldSeparator MIBFS;3400for (auto &MIB : AI.MIBs) {3401Out << MIBFS;3402Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);3403Out << ", stackIds: (";3404FieldSeparator SIDFS;3405for (auto Id : MIB.StackIdIndices) {3406Out << SIDFS;3407Out << TheIndex->getStackIdAtIndex(Id);3408}3409Out << "))";3410}3411Out << "))";3412}3413Out << ")";3414}34153416if (!FS->callsites().empty()) {3417Out << ", callsites: (";3418FieldSeparator SNFS;3419for (auto &CI : FS->callsites()) {3420Out << SNFS;3421if (CI.Callee)3422Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());3423else3424Out << "(callee: null";3425Out << ", clones: (";3426FieldSeparator VFS;3427for (auto V : CI.Clones) {3428Out << VFS;3429Out << V;3430}3431Out << "), stackIds: (";3432FieldSeparator SIDFS;3433for (auto Id : CI.StackIdIndices) {3434Out << SIDFS;3435Out << TheIndex->getStackIdAtIndex(Id);3436}3437Out << "))";3438}3439Out << ")";3440}34413442auto PrintRange = [&](const ConstantRange &Range) {3443Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";3444};34453446if (!FS->paramAccesses().empty()) {3447Out << ", params: (";3448FieldSeparator IFS;3449for (auto &PS : FS->paramAccesses()) {3450Out << IFS;3451Out << "(param: " << PS.ParamNo;3452Out << ", offset: ";3453PrintRange(PS.Use);3454if (!PS.Calls.empty()) {3455Out << ", calls: (";3456FieldSeparator IFS;3457for (auto &Call : PS.Calls) {3458Out << IFS;3459Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());3460Out << ", param: " << Call.ParamNo;3461Out << ", offset: ";3462PrintRange(Call.Offsets);3463Out << ")";3464}3465Out << ")";3466}3467Out << ")";3468}3469Out << ")";3470}3471}34723473void AssemblyWriter::printTypeIdInfo(3474const FunctionSummary::TypeIdInfo &TIDInfo) {3475Out << ", typeIdInfo: (";3476FieldSeparator TIDFS;3477if (!TIDInfo.TypeTests.empty()) {3478Out << TIDFS;3479Out << "typeTests: (";3480FieldSeparator FS;3481for (auto &GUID : TIDInfo.TypeTests) {3482auto TidIter = TheIndex->typeIds().equal_range(GUID);3483if (TidIter.first == TidIter.second) {3484Out << FS;3485Out << GUID;3486continue;3487}3488// Print all type id that correspond to this GUID.3489for (auto It = TidIter.first; It != TidIter.second; ++It) {3490Out << FS;3491auto Slot = Machine.getTypeIdSlot(It->second.first);3492assert(Slot != -1);3493Out << "^" << Slot;3494}3495}3496Out << ")";3497}3498if (!TIDInfo.TypeTestAssumeVCalls.empty()) {3499Out << TIDFS;3500printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");3501}3502if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {3503Out << TIDFS;3504printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");3505}3506if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {3507Out << TIDFS;3508printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,3509"typeTestAssumeConstVCalls");3510}3511if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {3512Out << TIDFS;3513printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,3514"typeCheckedLoadConstVCalls");3515}3516Out << ")";3517}35183519void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {3520auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);3521if (TidIter.first == TidIter.second) {3522Out << "vFuncId: (";3523Out << "guid: " << VFId.GUID;3524Out << ", offset: " << VFId.Offset;3525Out << ")";3526return;3527}3528// Print all type id that correspond to this GUID.3529FieldSeparator FS;3530for (auto It = TidIter.first; It != TidIter.second; ++It) {3531Out << FS;3532Out << "vFuncId: (";3533auto Slot = Machine.getTypeIdSlot(It->second.first);3534assert(Slot != -1);3535Out << "^" << Slot;3536Out << ", offset: " << VFId.Offset;3537Out << ")";3538}3539}35403541void AssemblyWriter::printNonConstVCalls(3542const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {3543Out << Tag << ": (";3544FieldSeparator FS;3545for (auto &VFuncId : VCallList) {3546Out << FS;3547printVFuncId(VFuncId);3548}3549Out << ")";3550}35513552void AssemblyWriter::printConstVCalls(3553const std::vector<FunctionSummary::ConstVCall> &VCallList,3554const char *Tag) {3555Out << Tag << ": (";3556FieldSeparator FS;3557for (auto &ConstVCall : VCallList) {3558Out << FS;3559Out << "(";3560printVFuncId(ConstVCall.VFunc);3561if (!ConstVCall.Args.empty()) {3562Out << ", ";3563printArgs(ConstVCall.Args);3564}3565Out << ")";3566}3567Out << ")";3568}35693570void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {3571GlobalValueSummary::GVFlags GVFlags = Summary.flags();3572GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;3573Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";3574Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())3575<< ", flags: (";3576Out << "linkage: " << getLinkageName(LT);3577Out << ", visibility: "3578<< getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);3579Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;3580Out << ", live: " << GVFlags.Live;3581Out << ", dsoLocal: " << GVFlags.DSOLocal;3582Out << ", canAutoHide: " << GVFlags.CanAutoHide;3583Out << ", importType: "3584<< getImportTypeName(GlobalValueSummary::ImportKind(GVFlags.ImportType));3585Out << ")";35863587if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)3588printAliasSummary(cast<AliasSummary>(&Summary));3589else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)3590printFunctionSummary(cast<FunctionSummary>(&Summary));3591else3592printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));35933594auto RefList = Summary.refs();3595if (!RefList.empty()) {3596Out << ", refs: (";3597FieldSeparator FS;3598for (auto &Ref : RefList) {3599Out << FS;3600if (Ref.isReadOnly())3601Out << "readonly ";3602else if (Ref.isWriteOnly())3603Out << "writeonly ";3604Out << "^" << Machine.getGUIDSlot(Ref.getGUID());3605}3606Out << ")";3607}36083609Out << ")";3610}36113612void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {3613Out << "^" << Slot << " = gv: (";3614if (!VI.name().empty())3615Out << "name: \"" << VI.name() << "\"";3616else3617Out << "guid: " << VI.getGUID();3618if (!VI.getSummaryList().empty()) {3619Out << ", summaries: (";3620FieldSeparator FS;3621for (auto &Summary : VI.getSummaryList()) {3622Out << FS;3623printSummary(*Summary);3624}3625Out << ")";3626}3627Out << ")";3628if (!VI.name().empty())3629Out << " ; guid = " << VI.getGUID();3630Out << "\n";3631}36323633static void printMetadataIdentifier(StringRef Name,3634formatted_raw_ostream &Out) {3635if (Name.empty()) {3636Out << "<empty name> ";3637} else {3638unsigned char FirstC = static_cast<unsigned char>(Name[0]);3639if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||3640FirstC == '_')3641Out << FirstC;3642else3643Out << '\\' << hexdigit(FirstC >> 4) << hexdigit(FirstC & 0x0F);3644for (unsigned i = 1, e = Name.size(); i != e; ++i) {3645unsigned char C = Name[i];3646if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')3647Out << C;3648else3649Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);3650}3651}3652}36533654void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {3655Out << '!';3656printMetadataIdentifier(NMD->getName(), Out);3657Out << " = !{";3658for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {3659if (i)3660Out << ", ";36613662// Write DIExpressions inline.3663// FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.3664MDNode *Op = NMD->getOperand(i);3665if (auto *Expr = dyn_cast<DIExpression>(Op)) {3666writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());3667continue;3668}36693670int Slot = Machine.getMetadataSlot(Op);3671if (Slot == -1)3672Out << "<badref>";3673else3674Out << '!' << Slot;3675}3676Out << "}\n";3677}36783679static void PrintVisibility(GlobalValue::VisibilityTypes Vis,3680formatted_raw_ostream &Out) {3681switch (Vis) {3682case GlobalValue::DefaultVisibility: break;3683case GlobalValue::HiddenVisibility: Out << "hidden "; break;3684case GlobalValue::ProtectedVisibility: Out << "protected "; break;3685}3686}36873688static void PrintDSOLocation(const GlobalValue &GV,3689formatted_raw_ostream &Out) {3690if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())3691Out << "dso_local ";3692}36933694static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,3695formatted_raw_ostream &Out) {3696switch (SCT) {3697case GlobalValue::DefaultStorageClass: break;3698case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;3699case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;3700}3701}37023703static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,3704formatted_raw_ostream &Out) {3705switch (TLM) {3706case GlobalVariable::NotThreadLocal:3707break;3708case GlobalVariable::GeneralDynamicTLSModel:3709Out << "thread_local ";3710break;3711case GlobalVariable::LocalDynamicTLSModel:3712Out << "thread_local(localdynamic) ";3713break;3714case GlobalVariable::InitialExecTLSModel:3715Out << "thread_local(initialexec) ";3716break;3717case GlobalVariable::LocalExecTLSModel:3718Out << "thread_local(localexec) ";3719break;3720}3721}37223723static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {3724switch (UA) {3725case GlobalVariable::UnnamedAddr::None:3726return "";3727case GlobalVariable::UnnamedAddr::Local:3728return "local_unnamed_addr";3729case GlobalVariable::UnnamedAddr::Global:3730return "unnamed_addr";3731}3732llvm_unreachable("Unknown UnnamedAddr");3733}37343735static void maybePrintComdat(formatted_raw_ostream &Out,3736const GlobalObject &GO) {3737const Comdat *C = GO.getComdat();3738if (!C)3739return;37403741if (isa<GlobalVariable>(GO))3742Out << ',';3743Out << " comdat";37443745if (GO.getName() == C->getName())3746return;37473748Out << '(';3749PrintLLVMName(Out, C->getName(), ComdatPrefix);3750Out << ')';3751}37523753void AssemblyWriter::printGlobal(const GlobalVariable *GV) {3754if (GV->isMaterializable())3755Out << "; Materializable\n";37563757AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());3758WriteAsOperandInternal(Out, GV, WriterCtx);3759Out << " = ";37603761if (!GV->hasInitializer() && GV->hasExternalLinkage())3762Out << "external ";37633764Out << getLinkageNameWithSpace(GV->getLinkage());3765PrintDSOLocation(*GV, Out);3766PrintVisibility(GV->getVisibility(), Out);3767PrintDLLStorageClass(GV->getDLLStorageClass(), Out);3768PrintThreadLocalModel(GV->getThreadLocalMode(), Out);3769StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());3770if (!UA.empty())3771Out << UA << ' ';37723773if (unsigned AddressSpace = GV->getType()->getAddressSpace())3774Out << "addrspace(" << AddressSpace << ") ";3775if (GV->isExternallyInitialized()) Out << "externally_initialized ";3776Out << (GV->isConstant() ? "constant " : "global ");3777TypePrinter.print(GV->getValueType(), Out);37783779if (GV->hasInitializer()) {3780Out << ' ';3781writeOperand(GV->getInitializer(), false);3782}37833784if (GV->hasSection()) {3785Out << ", section \"";3786printEscapedString(GV->getSection(), Out);3787Out << '"';3788}3789if (GV->hasPartition()) {3790Out << ", partition \"";3791printEscapedString(GV->getPartition(), Out);3792Out << '"';3793}3794if (auto CM = GV->getCodeModel()) {3795Out << ", code_model \"";3796switch (*CM) {3797case CodeModel::Tiny:3798Out << "tiny";3799break;3800case CodeModel::Small:3801Out << "small";3802break;3803case CodeModel::Kernel:3804Out << "kernel";3805break;3806case CodeModel::Medium:3807Out << "medium";3808break;3809case CodeModel::Large:3810Out << "large";3811break;3812}3813Out << '"';3814}38153816using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;3817if (GV->hasSanitizerMetadata()) {3818SanitizerMetadata MD = GV->getSanitizerMetadata();3819if (MD.NoAddress)3820Out << ", no_sanitize_address";3821if (MD.NoHWAddress)3822Out << ", no_sanitize_hwaddress";3823if (MD.Memtag)3824Out << ", sanitize_memtag";3825if (MD.IsDynInit)3826Out << ", sanitize_address_dyninit";3827}38283829maybePrintComdat(Out, *GV);3830if (MaybeAlign A = GV->getAlign())3831Out << ", align " << A->value();38323833SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;3834GV->getAllMetadata(MDs);3835printMetadataAttachments(MDs, ", ");38363837auto Attrs = GV->getAttributes();3838if (Attrs.hasAttributes())3839Out << " #" << Machine.getAttributeGroupSlot(Attrs);38403841printInfoComment(*GV);3842}38433844void AssemblyWriter::printAlias(const GlobalAlias *GA) {3845if (GA->isMaterializable())3846Out << "; Materializable\n";38473848AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());3849WriteAsOperandInternal(Out, GA, WriterCtx);3850Out << " = ";38513852Out << getLinkageNameWithSpace(GA->getLinkage());3853PrintDSOLocation(*GA, Out);3854PrintVisibility(GA->getVisibility(), Out);3855PrintDLLStorageClass(GA->getDLLStorageClass(), Out);3856PrintThreadLocalModel(GA->getThreadLocalMode(), Out);3857StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());3858if (!UA.empty())3859Out << UA << ' ';38603861Out << "alias ";38623863TypePrinter.print(GA->getValueType(), Out);3864Out << ", ";38653866if (const Constant *Aliasee = GA->getAliasee()) {3867writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));3868} else {3869TypePrinter.print(GA->getType(), Out);3870Out << " <<NULL ALIASEE>>";3871}38723873if (GA->hasPartition()) {3874Out << ", partition \"";3875printEscapedString(GA->getPartition(), Out);3876Out << '"';3877}38783879printInfoComment(*GA);3880Out << '\n';3881}38823883void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {3884if (GI->isMaterializable())3885Out << "; Materializable\n";38863887AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());3888WriteAsOperandInternal(Out, GI, WriterCtx);3889Out << " = ";38903891Out << getLinkageNameWithSpace(GI->getLinkage());3892PrintDSOLocation(*GI, Out);3893PrintVisibility(GI->getVisibility(), Out);38943895Out << "ifunc ";38963897TypePrinter.print(GI->getValueType(), Out);3898Out << ", ";38993900if (const Constant *Resolver = GI->getResolver()) {3901writeOperand(Resolver, !isa<ConstantExpr>(Resolver));3902} else {3903TypePrinter.print(GI->getType(), Out);3904Out << " <<NULL RESOLVER>>";3905}39063907if (GI->hasPartition()) {3908Out << ", partition \"";3909printEscapedString(GI->getPartition(), Out);3910Out << '"';3911}39123913printInfoComment(*GI);3914Out << '\n';3915}39163917void AssemblyWriter::printComdat(const Comdat *C) {3918C->print(Out);3919}39203921void AssemblyWriter::printTypeIdentities() {3922if (TypePrinter.empty())3923return;39243925Out << '\n';39263927// Emit all numbered types.3928auto &NumberedTypes = TypePrinter.getNumberedTypes();3929for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {3930Out << '%' << I << " = type ";39313932// Make sure we print out at least one level of the type structure, so3933// that we do not get %2 = type %23934TypePrinter.printStructBody(NumberedTypes[I], Out);3935Out << '\n';3936}39373938auto &NamedTypes = TypePrinter.getNamedTypes();3939for (StructType *NamedType : NamedTypes) {3940PrintLLVMName(Out, NamedType->getName(), LocalPrefix);3941Out << " = type ";39423943// Make sure we print out at least one level of the type structure, so3944// that we do not get %FILE = type %FILE3945TypePrinter.printStructBody(NamedType, Out);3946Out << '\n';3947}3948}39493950/// printFunction - Print all aspects of a function.3951void AssemblyWriter::printFunction(const Function *F) {3952if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);39533954if (F->isMaterializable())3955Out << "; Materializable\n";39563957const AttributeList &Attrs = F->getAttributes();3958if (Attrs.hasFnAttrs()) {3959AttributeSet AS = Attrs.getFnAttrs();3960std::string AttrStr;39613962for (const Attribute &Attr : AS) {3963if (!Attr.isStringAttribute()) {3964if (!AttrStr.empty()) AttrStr += ' ';3965AttrStr += Attr.getAsString();3966}3967}39683969if (!AttrStr.empty())3970Out << "; Function Attrs: " << AttrStr << '\n';3971}39723973Machine.incorporateFunction(F);39743975if (F->isDeclaration()) {3976Out << "declare";3977SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;3978F->getAllMetadata(MDs);3979printMetadataAttachments(MDs, " ");3980Out << ' ';3981} else3982Out << "define ";39833984Out << getLinkageNameWithSpace(F->getLinkage());3985PrintDSOLocation(*F, Out);3986PrintVisibility(F->getVisibility(), Out);3987PrintDLLStorageClass(F->getDLLStorageClass(), Out);39883989// Print the calling convention.3990if (F->getCallingConv() != CallingConv::C) {3991PrintCallingConv(F->getCallingConv(), Out);3992Out << " ";3993}39943995FunctionType *FT = F->getFunctionType();3996if (Attrs.hasRetAttrs())3997Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';3998TypePrinter.print(F->getReturnType(), Out);3999AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());4000Out << ' ';4001WriteAsOperandInternal(Out, F, WriterCtx);4002Out << '(';40034004// Loop over the arguments, printing them...4005if (F->isDeclaration() && !IsForDebug) {4006// We're only interested in the type here - don't print argument names.4007for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {4008// Insert commas as we go... the first arg doesn't get a comma4009if (I)4010Out << ", ";4011// Output type...4012TypePrinter.print(FT->getParamType(I), Out);40134014AttributeSet ArgAttrs = Attrs.getParamAttrs(I);4015if (ArgAttrs.hasAttributes()) {4016Out << ' ';4017writeAttributeSet(ArgAttrs);4018}4019}4020} else {4021// The arguments are meaningful here, print them in detail.4022for (const Argument &Arg : F->args()) {4023// Insert commas as we go... the first arg doesn't get a comma4024if (Arg.getArgNo() != 0)4025Out << ", ";4026printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));4027}4028}40294030// Finish printing arguments...4031if (FT->isVarArg()) {4032if (FT->getNumParams()) Out << ", ";4033Out << "..."; // Output varargs portion of signature!4034}4035Out << ')';4036StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());4037if (!UA.empty())4038Out << ' ' << UA;4039// We print the function address space if it is non-zero or if we are writing4040// a module with a non-zero program address space or if there is no valid4041// Module* so that the file can be parsed without the datalayout string.4042const Module *Mod = F->getParent();4043if (F->getAddressSpace() != 0 || !Mod ||4044Mod->getDataLayout().getProgramAddressSpace() != 0)4045Out << " addrspace(" << F->getAddressSpace() << ")";4046if (Attrs.hasFnAttrs())4047Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());4048if (F->hasSection()) {4049Out << " section \"";4050printEscapedString(F->getSection(), Out);4051Out << '"';4052}4053if (F->hasPartition()) {4054Out << " partition \"";4055printEscapedString(F->getPartition(), Out);4056Out << '"';4057}4058maybePrintComdat(Out, *F);4059if (MaybeAlign A = F->getAlign())4060Out << " align " << A->value();4061if (F->hasGC())4062Out << " gc \"" << F->getGC() << '"';4063if (F->hasPrefixData()) {4064Out << " prefix ";4065writeOperand(F->getPrefixData(), true);4066}4067if (F->hasPrologueData()) {4068Out << " prologue ";4069writeOperand(F->getPrologueData(), true);4070}4071if (F->hasPersonalityFn()) {4072Out << " personality ";4073writeOperand(F->getPersonalityFn(), /*PrintType=*/true);4074}40754076if (F->isDeclaration()) {4077Out << '\n';4078} else {4079SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;4080F->getAllMetadata(MDs);4081printMetadataAttachments(MDs, " ");40824083Out << " {";4084// Output all of the function's basic blocks.4085for (const BasicBlock &BB : *F)4086printBasicBlock(&BB);40874088// Output the function's use-lists.4089printUseLists(F);40904091Out << "}\n";4092}40934094Machine.purgeFunction();4095}40964097/// printArgument - This member is called for every argument that is passed into4098/// the function. Simply print it out4099void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {4100// Output type...4101TypePrinter.print(Arg->getType(), Out);41024103// Output parameter attributes list4104if (Attrs.hasAttributes()) {4105Out << ' ';4106writeAttributeSet(Attrs);4107}41084109// Output name, if available...4110if (Arg->hasName()) {4111Out << ' ';4112PrintLLVMName(Out, Arg);4113} else {4114int Slot = Machine.getLocalSlot(Arg);4115assert(Slot != -1 && "expect argument in function here");4116Out << " %" << Slot;4117}4118}41194120/// printBasicBlock - This member is called for each basic block in a method.4121void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {4122bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();4123if (BB->hasName()) { // Print out the label if it exists...4124Out << "\n";4125PrintLLVMName(Out, BB->getName(), LabelPrefix);4126Out << ':';4127} else if (!IsEntryBlock) {4128Out << "\n";4129int Slot = Machine.getLocalSlot(BB);4130if (Slot != -1)4131Out << Slot << ":";4132else4133Out << "<badref>:";4134}41354136if (!IsEntryBlock) {4137// Output predecessors for the block.4138Out.PadToColumn(50);4139Out << ";";4140const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);41414142if (PI == PE) {4143Out << " No predecessors!";4144} else {4145Out << " preds = ";4146writeOperand(*PI, false);4147for (++PI; PI != PE; ++PI) {4148Out << ", ";4149writeOperand(*PI, false);4150}4151}4152}41534154Out << "\n";41554156if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);41574158// Output all of the instructions in the basic block...4159for (const Instruction &I : *BB) {4160for (const DbgRecord &DR : I.getDbgRecordRange())4161printDbgRecordLine(DR);4162printInstructionLine(I);4163}41644165if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);4166}41674168/// printInstructionLine - Print an instruction and a newline character.4169void AssemblyWriter::printInstructionLine(const Instruction &I) {4170printInstruction(I);4171Out << '\n';4172}41734174/// printGCRelocateComment - print comment after call to the gc.relocate4175/// intrinsic indicating base and derived pointer names.4176void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {4177Out << " ; (";4178writeOperand(Relocate.getBasePtr(), false);4179Out << ", ";4180writeOperand(Relocate.getDerivedPtr(), false);4181Out << ")";4182}41834184/// printInfoComment - Print a little comment after the instruction indicating4185/// which slot it occupies.4186void AssemblyWriter::printInfoComment(const Value &V) {4187if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))4188printGCRelocateComment(*Relocate);41894190if (AnnotationWriter) {4191AnnotationWriter->printInfoComment(V, Out);4192}4193}41944195static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,4196raw_ostream &Out) {4197// We print the address space of the call if it is non-zero.4198if (Operand == nullptr) {4199Out << " <cannot get addrspace!>";4200return;4201}4202unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();4203bool PrintAddrSpace = CallAddrSpace != 0;4204if (!PrintAddrSpace) {4205const Module *Mod = getModuleFromVal(I);4206// We also print it if it is zero but not equal to the program address space4207// or if we can't find a valid Module* to make it possible to parse4208// the resulting file even without a datalayout string.4209if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)4210PrintAddrSpace = true;4211}4212if (PrintAddrSpace)4213Out << " addrspace(" << CallAddrSpace << ")";4214}42154216// This member is called for each Instruction in a function..4217void AssemblyWriter::printInstruction(const Instruction &I) {4218if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);42194220// Print out indentation for an instruction.4221Out << " ";42224223// Print out name if it exists...4224if (I.hasName()) {4225PrintLLVMName(Out, &I);4226Out << " = ";4227} else if (!I.getType()->isVoidTy()) {4228// Print out the def slot taken.4229int SlotNum = Machine.getLocalSlot(&I);4230if (SlotNum == -1)4231Out << "<badref> = ";4232else4233Out << '%' << SlotNum << " = ";4234}42354236if (const CallInst *CI = dyn_cast<CallInst>(&I)) {4237if (CI->isMustTailCall())4238Out << "musttail ";4239else if (CI->isTailCall())4240Out << "tail ";4241else if (CI->isNoTailCall())4242Out << "notail ";4243}42444245// Print out the opcode...4246Out << I.getOpcodeName();42474248// If this is an atomic load or store, print out the atomic marker.4249if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||4250(isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))4251Out << " atomic";42524253if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())4254Out << " weak";42554256// If this is a volatile operation, print out the volatile marker.4257if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||4258(isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||4259(isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||4260(isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))4261Out << " volatile";42624263// Print out optimization information.4264WriteOptimizationInfo(Out, &I);42654266// Print out the compare instruction predicates4267if (const CmpInst *CI = dyn_cast<CmpInst>(&I))4268Out << ' ' << CI->getPredicate();42694270// Print out the atomicrmw operation4271if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))4272Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());42734274// Print out the type of the operands...4275const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;42764277// Special case conditional branches to swizzle the condition out to the front4278if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {4279const BranchInst &BI(cast<BranchInst>(I));4280Out << ' ';4281writeOperand(BI.getCondition(), true);4282Out << ", ";4283writeOperand(BI.getSuccessor(0), true);4284Out << ", ";4285writeOperand(BI.getSuccessor(1), true);42864287} else if (isa<SwitchInst>(I)) {4288const SwitchInst& SI(cast<SwitchInst>(I));4289// Special case switch instruction to get formatting nice and correct.4290Out << ' ';4291writeOperand(SI.getCondition(), true);4292Out << ", ";4293writeOperand(SI.getDefaultDest(), true);4294Out << " [";4295for (auto Case : SI.cases()) {4296Out << "\n ";4297writeOperand(Case.getCaseValue(), true);4298Out << ", ";4299writeOperand(Case.getCaseSuccessor(), true);4300}4301Out << "\n ]";4302} else if (isa<IndirectBrInst>(I)) {4303// Special case indirectbr instruction to get formatting nice and correct.4304Out << ' ';4305writeOperand(Operand, true);4306Out << ", [";43074308for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {4309if (i != 1)4310Out << ", ";4311writeOperand(I.getOperand(i), true);4312}4313Out << ']';4314} else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {4315Out << ' ';4316TypePrinter.print(I.getType(), Out);4317Out << ' ';43184319for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {4320if (op) Out << ", ";4321Out << "[ ";4322writeOperand(PN->getIncomingValue(op), false); Out << ", ";4323writeOperand(PN->getIncomingBlock(op), false); Out << " ]";4324}4325} else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {4326Out << ' ';4327writeOperand(I.getOperand(0), true);4328for (unsigned i : EVI->indices())4329Out << ", " << i;4330} else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {4331Out << ' ';4332writeOperand(I.getOperand(0), true); Out << ", ";4333writeOperand(I.getOperand(1), true);4334for (unsigned i : IVI->indices())4335Out << ", " << i;4336} else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {4337Out << ' ';4338TypePrinter.print(I.getType(), Out);4339if (LPI->isCleanup() || LPI->getNumClauses() != 0)4340Out << '\n';43414342if (LPI->isCleanup())4343Out << " cleanup";43444345for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {4346if (i != 0 || LPI->isCleanup()) Out << "\n";4347if (LPI->isCatch(i))4348Out << " catch ";4349else4350Out << " filter ";43514352writeOperand(LPI->getClause(i), true);4353}4354} else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {4355Out << " within ";4356writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);4357Out << " [";4358unsigned Op = 0;4359for (const BasicBlock *PadBB : CatchSwitch->handlers()) {4360if (Op > 0)4361Out << ", ";4362writeOperand(PadBB, /*PrintType=*/true);4363++Op;4364}4365Out << "] unwind ";4366if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())4367writeOperand(UnwindDest, /*PrintType=*/true);4368else4369Out << "to caller";4370} else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {4371Out << " within ";4372writeOperand(FPI->getParentPad(), /*PrintType=*/false);4373Out << " [";4374for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {4375if (Op > 0)4376Out << ", ";4377writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);4378}4379Out << ']';4380} else if (isa<ReturnInst>(I) && !Operand) {4381Out << " void";4382} else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {4383Out << " from ";4384writeOperand(CRI->getOperand(0), /*PrintType=*/false);43854386Out << " to ";4387writeOperand(CRI->getOperand(1), /*PrintType=*/true);4388} else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {4389Out << " from ";4390writeOperand(CRI->getOperand(0), /*PrintType=*/false);43914392Out << " unwind ";4393if (CRI->hasUnwindDest())4394writeOperand(CRI->getOperand(1), /*PrintType=*/true);4395else4396Out << "to caller";4397} else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {4398// Print the calling convention being used.4399if (CI->getCallingConv() != CallingConv::C) {4400Out << " ";4401PrintCallingConv(CI->getCallingConv(), Out);4402}44034404Operand = CI->getCalledOperand();4405FunctionType *FTy = CI->getFunctionType();4406Type *RetTy = FTy->getReturnType();4407const AttributeList &PAL = CI->getAttributes();44084409if (PAL.hasRetAttrs())4410Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);44114412// Only print addrspace(N) if necessary:4413maybePrintCallAddrSpace(Operand, &I, Out);44144415// If possible, print out the short form of the call instruction. We can4416// only do this if the first argument is a pointer to a nonvararg function,4417// and if the return type is not a pointer to a function.4418Out << ' ';4419TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);4420Out << ' ';4421writeOperand(Operand, false);4422Out << '(';4423for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {4424if (op > 0)4425Out << ", ";4426writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));4427}44284429// Emit an ellipsis if this is a musttail call in a vararg function. This4430// is only to aid readability, musttail calls forward varargs by default.4431if (CI->isMustTailCall() && CI->getParent() &&4432CI->getParent()->getParent() &&4433CI->getParent()->getParent()->isVarArg()) {4434if (CI->arg_size() > 0)4435Out << ", ";4436Out << "...";4437}44384439Out << ')';4440if (PAL.hasFnAttrs())4441Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());44424443writeOperandBundles(CI);4444} else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {4445Operand = II->getCalledOperand();4446FunctionType *FTy = II->getFunctionType();4447Type *RetTy = FTy->getReturnType();4448const AttributeList &PAL = II->getAttributes();44494450// Print the calling convention being used.4451if (II->getCallingConv() != CallingConv::C) {4452Out << " ";4453PrintCallingConv(II->getCallingConv(), Out);4454}44554456if (PAL.hasRetAttrs())4457Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);44584459// Only print addrspace(N) if necessary:4460maybePrintCallAddrSpace(Operand, &I, Out);44614462// If possible, print out the short form of the invoke instruction. We can4463// only do this if the first argument is a pointer to a nonvararg function,4464// and if the return type is not a pointer to a function.4465//4466Out << ' ';4467TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);4468Out << ' ';4469writeOperand(Operand, false);4470Out << '(';4471for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {4472if (op)4473Out << ", ";4474writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));4475}44764477Out << ')';4478if (PAL.hasFnAttrs())4479Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());44804481writeOperandBundles(II);44824483Out << "\n to ";4484writeOperand(II->getNormalDest(), true);4485Out << " unwind ";4486writeOperand(II->getUnwindDest(), true);4487} else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {4488Operand = CBI->getCalledOperand();4489FunctionType *FTy = CBI->getFunctionType();4490Type *RetTy = FTy->getReturnType();4491const AttributeList &PAL = CBI->getAttributes();44924493// Print the calling convention being used.4494if (CBI->getCallingConv() != CallingConv::C) {4495Out << " ";4496PrintCallingConv(CBI->getCallingConv(), Out);4497}44984499if (PAL.hasRetAttrs())4500Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);45014502// If possible, print out the short form of the callbr instruction. We can4503// only do this if the first argument is a pointer to a nonvararg function,4504// and if the return type is not a pointer to a function.4505//4506Out << ' ';4507TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);4508Out << ' ';4509writeOperand(Operand, false);4510Out << '(';4511for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {4512if (op)4513Out << ", ";4514writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));4515}45164517Out << ')';4518if (PAL.hasFnAttrs())4519Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());45204521writeOperandBundles(CBI);45224523Out << "\n to ";4524writeOperand(CBI->getDefaultDest(), true);4525Out << " [";4526for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {4527if (i != 0)4528Out << ", ";4529writeOperand(CBI->getIndirectDest(i), true);4530}4531Out << ']';4532} else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {4533Out << ' ';4534if (AI->isUsedWithInAlloca())4535Out << "inalloca ";4536if (AI->isSwiftError())4537Out << "swifterror ";4538TypePrinter.print(AI->getAllocatedType(), Out);45394540// Explicitly write the array size if the code is broken, if it's an array4541// allocation, or if the type is not canonical for scalar allocations. The4542// latter case prevents the type from mutating when round-tripping through4543// assembly.4544if (!AI->getArraySize() || AI->isArrayAllocation() ||4545!AI->getArraySize()->getType()->isIntegerTy(32)) {4546Out << ", ";4547writeOperand(AI->getArraySize(), true);4548}4549if (MaybeAlign A = AI->getAlign()) {4550Out << ", align " << A->value();4551}45524553unsigned AddrSpace = AI->getAddressSpace();4554if (AddrSpace != 0) {4555Out << ", addrspace(" << AddrSpace << ')';4556}4557} else if (isa<CastInst>(I)) {4558if (Operand) {4559Out << ' ';4560writeOperand(Operand, true); // Work with broken code4561}4562Out << " to ";4563TypePrinter.print(I.getType(), Out);4564} else if (isa<VAArgInst>(I)) {4565if (Operand) {4566Out << ' ';4567writeOperand(Operand, true); // Work with broken code4568}4569Out << ", ";4570TypePrinter.print(I.getType(), Out);4571} else if (Operand) { // Print the normal way.4572if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {4573Out << ' ';4574TypePrinter.print(GEP->getSourceElementType(), Out);4575Out << ',';4576} else if (const auto *LI = dyn_cast<LoadInst>(&I)) {4577Out << ' ';4578TypePrinter.print(LI->getType(), Out);4579Out << ',';4580}45814582// PrintAllTypes - Instructions who have operands of all the same type4583// omit the type from all but the first operand. If the instruction has4584// different type operands (for example br), then they are all printed.4585bool PrintAllTypes = false;4586Type *TheType = Operand->getType();45874588// Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all4589// types.4590if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||4591isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||4592isa<AtomicRMWInst>(I)) {4593PrintAllTypes = true;4594} else {4595for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {4596Operand = I.getOperand(i);4597// note that Operand shouldn't be null, but the test helps make dump()4598// more tolerant of malformed IR4599if (Operand && Operand->getType() != TheType) {4600PrintAllTypes = true; // We have differing types! Print them all!4601break;4602}4603}4604}46054606if (!PrintAllTypes) {4607Out << ' ';4608TypePrinter.print(TheType, Out);4609}46104611Out << ' ';4612for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {4613if (i) Out << ", ";4614writeOperand(I.getOperand(i), PrintAllTypes);4615}4616}46174618// Print atomic ordering/alignment for memory operations4619if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {4620if (LI->isAtomic())4621writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());4622if (MaybeAlign A = LI->getAlign())4623Out << ", align " << A->value();4624} else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {4625if (SI->isAtomic())4626writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());4627if (MaybeAlign A = SI->getAlign())4628Out << ", align " << A->value();4629} else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {4630writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),4631CXI->getFailureOrdering(), CXI->getSyncScopeID());4632Out << ", align " << CXI->getAlign().value();4633} else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {4634writeAtomic(RMWI->getContext(), RMWI->getOrdering(),4635RMWI->getSyncScopeID());4636Out << ", align " << RMWI->getAlign().value();4637} else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {4638writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());4639} else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {4640PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());4641}46424643// Print Metadata info.4644SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;4645I.getAllMetadata(InstMD);4646printMetadataAttachments(InstMD, ", ");46474648// Print a nice comment.4649printInfoComment(I);4650}46514652void AssemblyWriter::printDbgMarker(const DbgMarker &Marker) {4653// There's no formal representation of a DbgMarker -- print purely as a4654// debugging aid.4655for (const DbgRecord &DPR : Marker.StoredDbgRecords) {4656printDbgRecord(DPR);4657Out << "\n";4658}46594660Out << " DbgMarker -> { ";4661printInstruction(*Marker.MarkedInstr);4662Out << " }";4663return;4664}46654666void AssemblyWriter::printDbgRecord(const DbgRecord &DR) {4667if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR))4668printDbgVariableRecord(*DVR);4669else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR))4670printDbgLabelRecord(*DLR);4671else4672llvm_unreachable("Unexpected DbgRecord kind");4673}46744675void AssemblyWriter::printDbgVariableRecord(const DbgVariableRecord &DVR) {4676auto WriterCtx = getContext();4677Out << "#dbg_";4678switch (DVR.getType()) {4679case DbgVariableRecord::LocationType::Value:4680Out << "value";4681break;4682case DbgVariableRecord::LocationType::Declare:4683Out << "declare";4684break;4685case DbgVariableRecord::LocationType::Assign:4686Out << "assign";4687break;4688default:4689llvm_unreachable(4690"Tried to print a DbgVariableRecord with an invalid LocationType!");4691}4692Out << "(";4693WriteAsOperandInternal(Out, DVR.getRawLocation(), WriterCtx, true);4694Out << ", ";4695WriteAsOperandInternal(Out, DVR.getRawVariable(), WriterCtx, true);4696Out << ", ";4697WriteAsOperandInternal(Out, DVR.getRawExpression(), WriterCtx, true);4698Out << ", ";4699if (DVR.isDbgAssign()) {4700WriteAsOperandInternal(Out, DVR.getRawAssignID(), WriterCtx, true);4701Out << ", ";4702WriteAsOperandInternal(Out, DVR.getRawAddress(), WriterCtx, true);4703Out << ", ";4704WriteAsOperandInternal(Out, DVR.getRawAddressExpression(), WriterCtx, true);4705Out << ", ";4706}4707WriteAsOperandInternal(Out, DVR.getDebugLoc().getAsMDNode(), WriterCtx, true);4708Out << ")";4709}47104711/// printDbgRecordLine - Print a DbgRecord with indentation and a newline4712/// character.4713void AssemblyWriter::printDbgRecordLine(const DbgRecord &DR) {4714// Print lengthier indentation to bring out-of-line with instructions.4715Out << " ";4716printDbgRecord(DR);4717Out << '\n';4718}47194720void AssemblyWriter::printDbgLabelRecord(const DbgLabelRecord &Label) {4721auto WriterCtx = getContext();4722Out << "#dbg_label(";4723WriteAsOperandInternal(Out, Label.getRawLabel(), WriterCtx, true);4724Out << ", ";4725WriteAsOperandInternal(Out, Label.getDebugLoc(), WriterCtx, true);4726Out << ")";4727}47284729void AssemblyWriter::printMetadataAttachments(4730const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,4731StringRef Separator) {4732if (MDs.empty())4733return;47344735if (MDNames.empty())4736MDs[0].second->getContext().getMDKindNames(MDNames);47374738auto WriterCtx = getContext();4739for (const auto &I : MDs) {4740unsigned Kind = I.first;4741Out << Separator;4742if (Kind < MDNames.size()) {4743Out << "!";4744printMetadataIdentifier(MDNames[Kind], Out);4745} else4746Out << "!<unknown kind #" << Kind << ">";4747Out << ' ';4748WriteAsOperandInternal(Out, I.second, WriterCtx);4749}4750}47514752void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {4753Out << '!' << Slot << " = ";4754printMDNodeBody(Node);4755Out << "\n";4756}47574758void AssemblyWriter::writeAllMDNodes() {4759SmallVector<const MDNode *, 16> Nodes;4760Nodes.resize(Machine.mdn_size());4761for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))4762Nodes[I.second] = cast<MDNode>(I.first);47634764for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {4765writeMDNode(i, Nodes[i]);4766}4767}47684769void AssemblyWriter::printMDNodeBody(const MDNode *Node) {4770auto WriterCtx = getContext();4771WriteMDNodeBodyInternal(Out, Node, WriterCtx);4772}47734774void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {4775if (!Attr.isTypeAttribute()) {4776Out << Attr.getAsString(InAttrGroup);4777return;4778}47794780Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());4781if (Type *Ty = Attr.getValueAsType()) {4782Out << '(';4783TypePrinter.print(Ty, Out);4784Out << ')';4785}4786}47874788void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,4789bool InAttrGroup) {4790bool FirstAttr = true;4791for (const auto &Attr : AttrSet) {4792if (!FirstAttr)4793Out << ' ';4794writeAttribute(Attr, InAttrGroup);4795FirstAttr = false;4796}4797}47984799void AssemblyWriter::writeAllAttributeGroups() {4800std::vector<std::pair<AttributeSet, unsigned>> asVec;4801asVec.resize(Machine.as_size());48024803for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))4804asVec[I.second] = I;48054806for (const auto &I : asVec)4807Out << "attributes #" << I.second << " = { "4808<< I.first.getAsString(true) << " }\n";4809}48104811void AssemblyWriter::printUseListOrder(const Value *V,4812const std::vector<unsigned> &Shuffle) {4813bool IsInFunction = Machine.getFunction();4814if (IsInFunction)4815Out << " ";48164817Out << "uselistorder";4818if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {4819Out << "_bb ";4820writeOperand(BB->getParent(), false);4821Out << ", ";4822writeOperand(BB, false);4823} else {4824Out << " ";4825writeOperand(V, true);4826}4827Out << ", { ";48284829assert(Shuffle.size() >= 2 && "Shuffle too small");4830Out << Shuffle[0];4831for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)4832Out << ", " << Shuffle[I];4833Out << " }\n";4834}48354836void AssemblyWriter::printUseLists(const Function *F) {4837auto It = UseListOrders.find(F);4838if (It == UseListOrders.end())4839return;48404841Out << "\n; uselistorder directives\n";4842for (const auto &Pair : It->second)4843printUseListOrder(Pair.first, Pair.second);4844}48454846//===----------------------------------------------------------------------===//4847// External Interface declarations4848//===----------------------------------------------------------------------===//48494850void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,4851bool ShouldPreserveUseListOrder,4852bool IsForDebug) const {4853SlotTracker SlotTable(this->getParent());4854formatted_raw_ostream OS(ROS);4855AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,4856IsForDebug,4857ShouldPreserveUseListOrder);4858W.printFunction(this);4859}48604861void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,4862bool ShouldPreserveUseListOrder,4863bool IsForDebug) const {4864SlotTracker SlotTable(this->getParent());4865formatted_raw_ostream OS(ROS);4866AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,4867IsForDebug,4868ShouldPreserveUseListOrder);4869W.printBasicBlock(this);4870}48714872void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,4873bool ShouldPreserveUseListOrder, bool IsForDebug) const {4874SlotTracker SlotTable(this);4875formatted_raw_ostream OS(ROS);4876AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,4877ShouldPreserveUseListOrder);4878W.printModule(this);4879}48804881void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {4882SlotTracker SlotTable(getParent());4883formatted_raw_ostream OS(ROS);4884AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);4885W.printNamedMDNode(this);4886}48874888void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,4889bool IsForDebug) const {4890std::optional<SlotTracker> LocalST;4891SlotTracker *SlotTable;4892if (auto *ST = MST.getMachine())4893SlotTable = ST;4894else {4895LocalST.emplace(getParent());4896SlotTable = &*LocalST;4897}48984899formatted_raw_ostream OS(ROS);4900AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);4901W.printNamedMDNode(this);4902}49034904void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {4905PrintLLVMName(ROS, getName(), ComdatPrefix);4906ROS << " = comdat ";49074908switch (getSelectionKind()) {4909case Comdat::Any:4910ROS << "any";4911break;4912case Comdat::ExactMatch:4913ROS << "exactmatch";4914break;4915case Comdat::Largest:4916ROS << "largest";4917break;4918case Comdat::NoDeduplicate:4919ROS << "nodeduplicate";4920break;4921case Comdat::SameSize:4922ROS << "samesize";4923break;4924}49254926ROS << '\n';4927}49284929void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {4930TypePrinting TP;4931TP.print(const_cast<Type*>(this), OS);49324933if (NoDetails)4934return;49354936// If the type is a named struct type, print the body as well.4937if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))4938if (!STy->isLiteral()) {4939OS << " = type ";4940TP.printStructBody(STy, OS);4941}4942}49434944static bool isReferencingMDNode(const Instruction &I) {4945if (const auto *CI = dyn_cast<CallInst>(&I))4946if (Function *F = CI->getCalledFunction())4947if (F->isIntrinsic())4948for (auto &Op : I.operands())4949if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))4950if (isa<MDNode>(V->getMetadata()))4951return true;4952return false;4953}49544955void DbgMarker::print(raw_ostream &ROS, bool IsForDebug) const {49564957ModuleSlotTracker MST(getModuleFromDPI(this), true);4958print(ROS, MST, IsForDebug);4959}49604961void DbgVariableRecord::print(raw_ostream &ROS, bool IsForDebug) const {49624963ModuleSlotTracker MST(getModuleFromDPI(this), true);4964print(ROS, MST, IsForDebug);4965}49664967void DbgMarker::print(raw_ostream &ROS, ModuleSlotTracker &MST,4968bool IsForDebug) const {4969formatted_raw_ostream OS(ROS);4970SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));4971SlotTracker &SlotTable =4972MST.getMachine() ? *MST.getMachine() : EmptySlotTable;4973auto incorporateFunction = [&](const Function *F) {4974if (F)4975MST.incorporateFunction(*F);4976};4977incorporateFunction(getParent() ? getParent()->getParent() : nullptr);4978AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);4979W.printDbgMarker(*this);4980}49814982void DbgLabelRecord::print(raw_ostream &ROS, bool IsForDebug) const {49834984ModuleSlotTracker MST(getModuleFromDPI(this), true);4985print(ROS, MST, IsForDebug);4986}49874988void DbgVariableRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,4989bool IsForDebug) const {4990formatted_raw_ostream OS(ROS);4991SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));4992SlotTracker &SlotTable =4993MST.getMachine() ? *MST.getMachine() : EmptySlotTable;4994auto incorporateFunction = [&](const Function *F) {4995if (F)4996MST.incorporateFunction(*F);4997};4998incorporateFunction(Marker && Marker->getParent()4999? Marker->getParent()->getParent()5000: nullptr);5001AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);5002W.printDbgVariableRecord(*this);5003}50045005void DbgLabelRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,5006bool IsForDebug) const {5007formatted_raw_ostream OS(ROS);5008SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));5009SlotTracker &SlotTable =5010MST.getMachine() ? *MST.getMachine() : EmptySlotTable;5011auto incorporateFunction = [&](const Function *F) {5012if (F)5013MST.incorporateFunction(*F);5014};5015incorporateFunction(Marker->getParent() ? Marker->getParent()->getParent()5016: nullptr);5017AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);5018W.printDbgLabelRecord(*this);5019}50205021void Value::print(raw_ostream &ROS, bool IsForDebug) const {5022bool ShouldInitializeAllMetadata = false;5023if (auto *I = dyn_cast<Instruction>(this))5024ShouldInitializeAllMetadata = isReferencingMDNode(*I);5025else if (isa<Function>(this) || isa<MetadataAsValue>(this))5026ShouldInitializeAllMetadata = true;50275028ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);5029print(ROS, MST, IsForDebug);5030}50315032void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,5033bool IsForDebug) const {5034formatted_raw_ostream OS(ROS);5035SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));5036SlotTracker &SlotTable =5037MST.getMachine() ? *MST.getMachine() : EmptySlotTable;5038auto incorporateFunction = [&](const Function *F) {5039if (F)5040MST.incorporateFunction(*F);5041};50425043if (const Instruction *I = dyn_cast<Instruction>(this)) {5044incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);5045AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);5046W.printInstruction(*I);5047} else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {5048incorporateFunction(BB->getParent());5049AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);5050W.printBasicBlock(BB);5051} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {5052AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);5053if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))5054W.printGlobal(V);5055else if (const Function *F = dyn_cast<Function>(GV))5056W.printFunction(F);5057else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))5058W.printAlias(A);5059else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))5060W.printIFunc(I);5061else5062llvm_unreachable("Unknown GlobalValue to print out!");5063} else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {5064V->getMetadata()->print(ROS, MST, getModuleFromVal(V));5065} else if (const Constant *C = dyn_cast<Constant>(this)) {5066TypePrinting TypePrinter;5067TypePrinter.print(C->getType(), OS);5068OS << ' ';5069AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());5070WriteConstantInternal(OS, C, WriterCtx);5071} else if (isa<InlineAsm>(this) || isa<Argument>(this)) {5072this->printAsOperand(OS, /* PrintType */ true, MST);5073} else {5074llvm_unreachable("Unknown value to print out!");5075}5076}50775078/// Print without a type, skipping the TypePrinting object.5079///5080/// \return \c true iff printing was successful.5081static bool printWithoutType(const Value &V, raw_ostream &O,5082SlotTracker *Machine, const Module *M) {5083if (V.hasName() || isa<GlobalValue>(V) ||5084(!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {5085AsmWriterContext WriterCtx(nullptr, Machine, M);5086WriteAsOperandInternal(O, &V, WriterCtx);5087return true;5088}5089return false;5090}50915092static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,5093ModuleSlotTracker &MST) {5094TypePrinting TypePrinter(MST.getModule());5095if (PrintType) {5096TypePrinter.print(V.getType(), O);5097O << ' ';5098}50995100AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());5101WriteAsOperandInternal(O, &V, WriterCtx);5102}51035104void Value::printAsOperand(raw_ostream &O, bool PrintType,5105const Module *M) const {5106if (!M)5107M = getModuleFromVal(this);51085109if (!PrintType)5110if (printWithoutType(*this, O, nullptr, M))5111return;51125113SlotTracker Machine(5114M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));5115ModuleSlotTracker MST(Machine, M);5116printAsOperandImpl(*this, O, PrintType, MST);5117}51185119void Value::printAsOperand(raw_ostream &O, bool PrintType,5120ModuleSlotTracker &MST) const {5121if (!PrintType)5122if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))5123return;51245125printAsOperandImpl(*this, O, PrintType, MST);5126}51275128/// Recursive version of printMetadataImpl.5129static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,5130AsmWriterContext &WriterCtx) {5131formatted_raw_ostream OS(ROS);5132WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);51335134auto *N = dyn_cast<MDNode>(&MD);5135if (!N || isa<DIExpression>(MD))5136return;51375138OS << " = ";5139WriteMDNodeBodyInternal(OS, N, WriterCtx);5140}51415142namespace {5143struct MDTreeAsmWriterContext : public AsmWriterContext {5144unsigned Level;5145// {Level, Printed string}5146using EntryTy = std::pair<unsigned, std::string>;5147SmallVector<EntryTy, 4> Buffer;51485149// Used to break the cycle in case there is any.5150SmallPtrSet<const Metadata *, 4> Visited;51515152raw_ostream &MainOS;51535154MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,5155raw_ostream &OS, const Metadata *InitMD)5156: AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}51575158void onWriteMetadataAsOperand(const Metadata *MD) override {5159if (!Visited.insert(MD).second)5160return;51615162std::string Str;5163raw_string_ostream SS(Str);5164++Level;5165// A placeholder entry to memorize the correct5166// position in buffer.5167Buffer.emplace_back(std::make_pair(Level, ""));5168unsigned InsertIdx = Buffer.size() - 1;51695170printMetadataImplRec(SS, *MD, *this);5171Buffer[InsertIdx].second = std::move(SS.str());5172--Level;5173}51745175~MDTreeAsmWriterContext() {5176for (const auto &Entry : Buffer) {5177MainOS << "\n";5178unsigned NumIndent = Entry.first * 2U;5179MainOS.indent(NumIndent) << Entry.second;5180}5181}5182};5183} // end anonymous namespace51845185static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,5186ModuleSlotTracker &MST, const Module *M,5187bool OnlyAsOperand, bool PrintAsTree = false) {5188formatted_raw_ostream OS(ROS);51895190TypePrinting TypePrinter(M);51915192std::unique_ptr<AsmWriterContext> WriterCtx;5193if (PrintAsTree && !OnlyAsOperand)5194WriterCtx = std::make_unique<MDTreeAsmWriterContext>(5195&TypePrinter, MST.getMachine(), M, OS, &MD);5196else5197WriterCtx =5198std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);51995200WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);52015202auto *N = dyn_cast<MDNode>(&MD);5203if (OnlyAsOperand || !N || isa<DIExpression>(MD))5204return;52055206OS << " = ";5207WriteMDNodeBodyInternal(OS, N, *WriterCtx);5208}52095210void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {5211ModuleSlotTracker MST(M, isa<MDNode>(this));5212printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);5213}52145215void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,5216const Module *M) const {5217printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);5218}52195220void Metadata::print(raw_ostream &OS, const Module *M,5221bool /*IsForDebug*/) const {5222ModuleSlotTracker MST(M, isa<MDNode>(this));5223printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);5224}52255226void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,5227const Module *M, bool /*IsForDebug*/) const {5228printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);5229}52305231void MDNode::printTree(raw_ostream &OS, const Module *M) const {5232ModuleSlotTracker MST(M, true);5233printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,5234/*PrintAsTree=*/true);5235}52365237void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,5238const Module *M) const {5239printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,5240/*PrintAsTree=*/true);5241}52425243void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {5244SlotTracker SlotTable(this);5245formatted_raw_ostream OS(ROS);5246AssemblyWriter W(OS, SlotTable, this, IsForDebug);5247W.printModuleSummaryIndex();5248}52495250void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,5251unsigned UB) const {5252SlotTracker *ST = MachineStorage.get();5253if (!ST)5254return;52555256for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))5257if (I.second >= LB && I.second < UB)5258L.push_back(std::make_pair(I.second, I.first));5259}52605261#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)5262// Value::dump - allow easy printing of Values from the debugger.5263LLVM_DUMP_METHOD5264void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }52655266// Value::dump - allow easy printing of Values from the debugger.5267LLVM_DUMP_METHOD5268void DbgMarker::dump() const {5269print(dbgs(), /*IsForDebug=*/true);5270dbgs() << '\n';5271}52725273// Value::dump - allow easy printing of Values from the debugger.5274LLVM_DUMP_METHOD5275void DbgRecord::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }52765277// Type::dump - allow easy printing of Types from the debugger.5278LLVM_DUMP_METHOD5279void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }52805281// Module::dump() - Allow printing of Modules from the debugger.5282LLVM_DUMP_METHOD5283void Module::dump() const {5284print(dbgs(), nullptr,5285/*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);5286}52875288// Allow printing of Comdats from the debugger.5289LLVM_DUMP_METHOD5290void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }52915292// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.5293LLVM_DUMP_METHOD5294void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }52955296LLVM_DUMP_METHOD5297void Metadata::dump() const { dump(nullptr); }52985299LLVM_DUMP_METHOD5300void Metadata::dump(const Module *M) const {5301print(dbgs(), M, /*IsForDebug=*/true);5302dbgs() << '\n';5303}53045305LLVM_DUMP_METHOD5306void MDNode::dumpTree() const { dumpTree(nullptr); }53075308LLVM_DUMP_METHOD5309void MDNode::dumpTree(const Module *M) const {5310printTree(dbgs(), M);5311dbgs() << '\n';5312}53135314// Allow printing of ModuleSummaryIndex from the debugger.5315LLVM_DUMP_METHOD5316void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }5317#endif531853195320