1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements `print` family of functions in classes like
11 // Module, Function, Value, etc. In-memory representation of those classes is
12 // converted to IR strings.
14 // Note that these routines must be extremely tolerant of various errors in the
15 // LLVM code, because it can be used for debugging transformations.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/iterator_range.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/AssemblyAnnotationWriter.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Comdat.h"
41 #include "llvm/IR/Constant.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalIFunc.h"
48 #include "llvm/IR/GlobalIndirectSymbol.h"
49 #include "llvm/IR/GlobalObject.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/GlobalVariable.h"
52 #include "llvm/IR/IRPrintingPasses.h"
53 #include "llvm/IR/InlineAsm.h"
54 #include "llvm/IR/InstrTypes.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/ModuleSlotTracker.h"
61 #include "llvm/IR/ModuleSummaryIndex.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/Statepoint.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/IR/TypeFinder.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/UseListOrder.h"
68 #include "llvm/IR/User.h"
69 #include "llvm/IR/Value.h"
70 #include "llvm/Support/AtomicOrdering.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/Format.h"
76 #include "llvm/Support/FormattedStream.h"
77 #include "llvm/Support/raw_ostream.h"
92 // Make virtual table appear in this compilation unit.
93 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
95 //===----------------------------------------------------------------------===//
97 //===----------------------------------------------------------------------===//
102 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
104 unsigned size() const { return IDs.size(); }
105 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
107 std::pair<unsigned, bool> lookup(const Value *V) const {
108 return IDs.lookup(V);
111 void index(const Value *V) {
112 // Explicitly sequence get-size and insert-value operations to avoid UB.
113 unsigned ID = IDs.size() + 1;
118 } // end anonymous namespace
120 static void orderValue(const Value *V, OrderMap &OM) {
121 if (OM.lookup(V).first)
124 if (const Constant *C = dyn_cast<Constant>(V))
125 if (C->getNumOperands() && !isa<GlobalValue>(C))
126 for (const Value *Op : C->operands())
127 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
130 // Note: we cannot cache this lookup above, since inserting into the map
131 // changes the map's size, and thus affects the other IDs.
135 static OrderMap orderModule(const Module *M) {
136 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
137 // and ValueEnumerator::incorporateFunction().
140 for (const GlobalVariable &G : M->globals()) {
141 if (G.hasInitializer())
142 if (!isa<GlobalValue>(G.getInitializer()))
143 orderValue(G.getInitializer(), OM);
146 for (const GlobalAlias &A : M->aliases()) {
147 if (!isa<GlobalValue>(A.getAliasee()))
148 orderValue(A.getAliasee(), OM);
151 for (const GlobalIFunc &I : M->ifuncs()) {
152 if (!isa<GlobalValue>(I.getResolver()))
153 orderValue(I.getResolver(), OM);
156 for (const Function &F : *M) {
157 for (const Use &U : F.operands())
158 if (!isa<GlobalValue>(U.get()))
159 orderValue(U.get(), OM);
163 if (F.isDeclaration())
166 for (const Argument &A : F.args())
168 for (const BasicBlock &BB : F) {
170 for (const Instruction &I : BB) {
171 for (const Value *Op : I.operands())
172 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
182 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
183 unsigned ID, const OrderMap &OM,
184 UseListOrderStack &Stack) {
185 // Predict use-list order for this one.
186 using Entry = std::pair<const Use *, unsigned>;
187 SmallVector<Entry, 64> List;
188 for (const Use &U : V->uses())
189 // Check if this user will be serialized.
190 if (OM.lookup(U.getUser()).first)
191 List.push_back(std::make_pair(&U, List.size()));
194 // We may have lost some users.
198 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
199 if (auto *BA = dyn_cast<BlockAddress>(V))
200 ID = OM.lookup(BA->getBasicBlock()).first;
201 llvm::sort(List, [&](const Entry &L, const Entry &R) {
202 const Use *LU = L.first;
203 const Use *RU = R.first;
207 auto LID = OM.lookup(LU->getUser()).first;
208 auto RID = OM.lookup(RU->getUser()).first;
210 // If ID is 4, then expect: 7 6 5 1 2 3.
224 // LID and RID are equal, so we have different operands of the same user.
225 // Assume operands are added in order for all instructions.
228 return LU->getOperandNo() < RU->getOperandNo();
229 return LU->getOperandNo() > RU->getOperandNo();
233 List.begin(), List.end(),
234 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
235 // Order is already correct.
238 // Store the shuffle.
239 Stack.emplace_back(V, F, List.size());
240 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
241 for (size_t I = 0, E = List.size(); I != E; ++I)
242 Stack.back().Shuffle[I] = List[I].second;
245 static void predictValueUseListOrder(const Value *V, const Function *F,
246 OrderMap &OM, UseListOrderStack &Stack) {
247 auto &IDPair = OM[V];
248 assert(IDPair.first && "Unmapped value");
250 // Already predicted.
253 // Do the actual prediction.
254 IDPair.second = true;
255 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
256 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
258 // Recursive descent into constants.
259 if (const Constant *C = dyn_cast<Constant>(V))
260 if (C->getNumOperands()) // Visit GlobalValues.
261 for (const Value *Op : C->operands())
262 if (isa<Constant>(Op)) // Visit GlobalValues.
263 predictValueUseListOrder(Op, F, OM, Stack);
266 static UseListOrderStack predictUseListOrder(const Module *M) {
267 OrderMap OM = orderModule(M);
269 // Use-list orders need to be serialized after all the users have been added
270 // to a value, or else the shuffles will be incomplete. Store them per
271 // function in a stack.
273 // Aside from function order, the order of values doesn't matter much here.
274 UseListOrderStack Stack;
276 // We want to visit the functions backward now so we can list function-local
277 // constants in the last Function they're used in. Module-level constants
278 // have already been visited above.
279 for (const Function &F : make_range(M->rbegin(), M->rend())) {
280 if (F.isDeclaration())
282 for (const BasicBlock &BB : F)
283 predictValueUseListOrder(&BB, &F, OM, Stack);
284 for (const Argument &A : F.args())
285 predictValueUseListOrder(&A, &F, OM, Stack);
286 for (const BasicBlock &BB : F)
287 for (const Instruction &I : BB)
288 for (const Value *Op : I.operands())
289 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
290 predictValueUseListOrder(Op, &F, OM, Stack);
291 for (const BasicBlock &BB : F)
292 for (const Instruction &I : BB)
293 predictValueUseListOrder(&I, &F, OM, Stack);
296 // Visit globals last.
297 for (const GlobalVariable &G : M->globals())
298 predictValueUseListOrder(&G, nullptr, OM, Stack);
299 for (const Function &F : *M)
300 predictValueUseListOrder(&F, nullptr, OM, Stack);
301 for (const GlobalAlias &A : M->aliases())
302 predictValueUseListOrder(&A, nullptr, OM, Stack);
303 for (const GlobalIFunc &I : M->ifuncs())
304 predictValueUseListOrder(&I, nullptr, OM, Stack);
305 for (const GlobalVariable &G : M->globals())
306 if (G.hasInitializer())
307 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
308 for (const GlobalAlias &A : M->aliases())
309 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
310 for (const GlobalIFunc &I : M->ifuncs())
311 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
312 for (const Function &F : *M)
313 for (const Use &U : F.operands())
314 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
319 static const Module *getModuleFromVal(const Value *V) {
320 if (const Argument *MA = dyn_cast<Argument>(V))
321 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
323 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
324 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
326 if (const Instruction *I = dyn_cast<Instruction>(V)) {
327 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
328 return M ? M->getParent() : nullptr;
331 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
332 return GV->getParent();
334 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
335 for (const User *U : MAV->users())
336 if (isa<Instruction>(U))
337 if (const Module *M = getModuleFromVal(U))
345 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
347 default: Out << "cc" << cc; break;
348 case CallingConv::Fast: Out << "fastcc"; break;
349 case CallingConv::Cold: Out << "coldcc"; break;
350 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
351 case CallingConv::AnyReg: Out << "anyregcc"; break;
352 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
353 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
354 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
355 case CallingConv::GHC: Out << "ghccc"; break;
356 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
357 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
358 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
359 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
360 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
361 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
362 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
363 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
364 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
365 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
366 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
367 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
368 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
369 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
370 case CallingConv::PTX_Device: Out << "ptx_device"; break;
371 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
372 case CallingConv::Win64: Out << "win64cc"; break;
373 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
374 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
375 case CallingConv::Swift: Out << "swiftcc"; break;
376 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
377 case CallingConv::HHVM: Out << "hhvmcc"; break;
378 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
379 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
380 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
381 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
382 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
383 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
384 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
385 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
386 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
398 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
399 assert(!Name.empty() && "Cannot get empty name!");
401 // Scan the name to see if it needs quotes first.
402 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
404 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
405 // By making this unsigned, the value passed in to isalnum will always be
406 // in the range 0-255. This is important when building with MSVC because
407 // its implementation will assert. This situation can arise when dealing
408 // with UTF-8 multibyte characters.
409 unsigned char C = Name[i];
410 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
418 // If we didn't need any quotes, just write out the name in one blast.
424 // Okay, we need quotes. Output the quotes and escape any scary characters as
427 printEscapedString(Name, OS);
431 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
432 /// (if the string only contains simple characters) or is surrounded with ""'s
433 /// (if it has special chars in it). Print it out.
434 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
450 printLLVMNameWithoutPrefix(OS, Name);
453 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
454 /// (if the string only contains simple characters) or is surrounded with ""'s
455 /// (if it has special chars in it). Print it out.
456 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
457 PrintLLVMName(OS, V->getName(),
458 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
465 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
467 TypePrinting(const TypePrinting &) = delete;
468 TypePrinting &operator=(const TypePrinting &) = delete;
470 /// The named types that are used by the current module.
471 TypeFinder &getNamedTypes();
473 /// The numbered types, number to type mapping.
474 std::vector<StructType *> &getNumberedTypes();
478 void print(Type *Ty, raw_ostream &OS);
480 void printStructBody(StructType *Ty, raw_ostream &OS);
483 void incorporateTypes();
485 /// A module to process lazily when needed. Set to nullptr as soon as used.
486 const Module *DeferredM;
488 TypeFinder NamedTypes;
490 // The numbered types, along with their value.
491 DenseMap<StructType *, unsigned> Type2Number;
493 std::vector<StructType *> NumberedTypes;
496 } // end anonymous namespace
498 TypeFinder &TypePrinting::getNamedTypes() {
503 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
506 // We know all the numbers that each type is used and we know that it is a
507 // dense assignment. Convert the map to an index table, if it's not done
508 // already (judging from the sizes):
509 if (NumberedTypes.size() == Type2Number.size())
510 return NumberedTypes;
512 NumberedTypes.resize(Type2Number.size());
513 for (const auto &P : Type2Number) {
514 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
515 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
516 NumberedTypes[P.second] = P.first;
518 return NumberedTypes;
521 bool TypePrinting::empty() {
523 return NamedTypes.empty() && Type2Number.empty();
526 void TypePrinting::incorporateTypes() {
530 NamedTypes.run(*DeferredM, false);
533 // The list of struct types we got back includes all the struct types, split
534 // the unnamed ones out to a numbering and remove the anonymous structs.
535 unsigned NextNumber = 0;
537 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
538 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
539 StructType *STy = *I;
541 // Ignore anonymous types.
542 if (STy->isLiteral())
545 if (STy->getName().empty())
546 Type2Number[STy] = NextNumber++;
551 NamedTypes.erase(NextToUse, NamedTypes.end());
554 /// Write the specified type to the specified raw_ostream, making use of type
555 /// names or up references to shorten the type name where possible.
556 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
557 switch (Ty->getTypeID()) {
558 case Type::VoidTyID: OS << "void"; return;
559 case Type::HalfTyID: OS << "half"; return;
560 case Type::FloatTyID: OS << "float"; return;
561 case Type::DoubleTyID: OS << "double"; return;
562 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
563 case Type::FP128TyID: OS << "fp128"; return;
564 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
565 case Type::LabelTyID: OS << "label"; return;
566 case Type::MetadataTyID: OS << "metadata"; return;
567 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
568 case Type::TokenTyID: OS << "token"; return;
569 case Type::IntegerTyID:
570 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
573 case Type::FunctionTyID: {
574 FunctionType *FTy = cast<FunctionType>(Ty);
575 print(FTy->getReturnType(), OS);
577 for (FunctionType::param_iterator I = FTy->param_begin(),
578 E = FTy->param_end(); I != E; ++I) {
579 if (I != FTy->param_begin())
583 if (FTy->isVarArg()) {
584 if (FTy->getNumParams()) OS << ", ";
590 case Type::StructTyID: {
591 StructType *STy = cast<StructType>(Ty);
593 if (STy->isLiteral())
594 return printStructBody(STy, OS);
596 if (!STy->getName().empty())
597 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
600 const auto I = Type2Number.find(STy);
601 if (I != Type2Number.end())
602 OS << '%' << I->second;
603 else // Not enumerated, print the hex address.
604 OS << "%\"type " << STy << '\"';
607 case Type::PointerTyID: {
608 PointerType *PTy = cast<PointerType>(Ty);
609 print(PTy->getElementType(), OS);
610 if (unsigned AddressSpace = PTy->getAddressSpace())
611 OS << " addrspace(" << AddressSpace << ')';
615 case Type::ArrayTyID: {
616 ArrayType *ATy = cast<ArrayType>(Ty);
617 OS << '[' << ATy->getNumElements() << " x ";
618 print(ATy->getElementType(), OS);
622 case Type::VectorTyID: {
623 VectorType *PTy = cast<VectorType>(Ty);
624 OS << "<" << PTy->getNumElements() << " x ";
625 print(PTy->getElementType(), OS);
630 llvm_unreachable("Invalid TypeID");
633 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
634 if (STy->isOpaque()) {
642 if (STy->getNumElements() == 0) {
645 StructType::element_iterator I = STy->element_begin();
648 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
661 //===----------------------------------------------------------------------===//
662 // SlotTracker Class: Enumerate slot numbers for unnamed values
663 //===----------------------------------------------------------------------===//
664 /// This class provides computation of slot numbers for LLVM Assembly writing.
668 /// ValueMap - A mapping of Values to slot numbers.
669 using ValueMap = DenseMap<const Value *, unsigned>;
672 /// TheModule - The module for which we are holding slot numbers.
673 const Module* TheModule;
675 /// TheFunction - The function for which we are holding slot numbers.
676 const Function* TheFunction = nullptr;
677 bool FunctionProcessed = false;
678 bool ShouldInitializeAllMetadata;
680 /// The summary index for which we are holding slot numbers.
681 const ModuleSummaryIndex *TheIndex = nullptr;
683 /// mMap - The slot map for the module level data.
687 /// fMap - The slot map for the function level data.
691 /// mdnMap - Map for MDNodes.
692 DenseMap<const MDNode*, unsigned> mdnMap;
693 unsigned mdnNext = 0;
695 /// asMap - The slot map for attribute sets.
696 DenseMap<AttributeSet, unsigned> asMap;
699 /// ModulePathMap - The slot map for Module paths used in the summary index.
700 StringMap<unsigned> ModulePathMap;
701 unsigned ModulePathNext = 0;
703 /// GUIDMap - The slot map for GUIDs used in the summary index.
704 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
705 unsigned GUIDNext = 0;
707 /// TypeIdMap - The slot map for type ids used in the summary index.
708 StringMap<unsigned> TypeIdMap;
709 unsigned TypeIdNext = 0;
712 /// Construct from a module.
714 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
715 /// functions, giving correct numbering for metadata referenced only from
716 /// within a function (even if no functions have been initialized).
717 explicit SlotTracker(const Module *M,
718 bool ShouldInitializeAllMetadata = false);
720 /// Construct from a function, starting out in incorp state.
722 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
723 /// functions, giving correct numbering for metadata referenced only from
724 /// within a function (even if no functions have been initialized).
725 explicit SlotTracker(const Function *F,
726 bool ShouldInitializeAllMetadata = false);
728 /// Construct from a module summary index.
729 explicit SlotTracker(const ModuleSummaryIndex *Index);
731 SlotTracker(const SlotTracker &) = delete;
732 SlotTracker &operator=(const SlotTracker &) = delete;
734 /// Return the slot number of the specified value in it's type
735 /// plane. If something is not in the SlotTracker, return -1.
736 int getLocalSlot(const Value *V);
737 int getGlobalSlot(const GlobalValue *V);
738 int getMetadataSlot(const MDNode *N);
739 int getAttributeGroupSlot(AttributeSet AS);
740 int getModulePathSlot(StringRef Path);
741 int getGUIDSlot(GlobalValue::GUID GUID);
742 int getTypeIdSlot(StringRef Id);
744 /// If you'd like to deal with a function instead of just a module, use
745 /// this method to get its data into the SlotTracker.
746 void incorporateFunction(const Function *F) {
748 FunctionProcessed = false;
751 const Function *getFunction() const { return TheFunction; }
753 /// After calling incorporateFunction, use this method to remove the
754 /// most recently incorporated function from the SlotTracker. This
755 /// will reset the state of the machine back to just the module contents.
756 void purgeFunction();
758 /// MDNode map iterators.
759 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
761 mdn_iterator mdn_begin() { return mdnMap.begin(); }
762 mdn_iterator mdn_end() { return mdnMap.end(); }
763 unsigned mdn_size() const { return mdnMap.size(); }
764 bool mdn_empty() const { return mdnMap.empty(); }
766 /// AttributeSet map iterators.
767 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
769 as_iterator as_begin() { return asMap.begin(); }
770 as_iterator as_end() { return asMap.end(); }
771 unsigned as_size() const { return asMap.size(); }
772 bool as_empty() const { return asMap.empty(); }
774 /// GUID map iterators.
775 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
777 /// These functions do the actual initialization.
778 inline void initializeIfNeeded();
779 void initializeIndexIfNeeded();
781 // Implementation Details
783 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
784 void CreateModuleSlot(const GlobalValue *V);
786 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
787 void CreateMetadataSlot(const MDNode *N);
789 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
790 void CreateFunctionSlot(const Value *V);
792 /// Insert the specified AttributeSet into the slot table.
793 void CreateAttributeSetSlot(AttributeSet AS);
795 inline void CreateModulePathSlot(StringRef Path);
796 void CreateGUIDSlot(GlobalValue::GUID GUID);
797 void CreateTypeIdSlot(StringRef Id);
799 /// Add all of the module level global variables (and their initializers)
800 /// and function declarations, but not the contents of those functions.
801 void processModule();
804 /// Add all of the functions arguments, basic blocks, and instructions.
805 void processFunction();
807 /// Add the metadata directly attached to a GlobalObject.
808 void processGlobalObjectMetadata(const GlobalObject &GO);
810 /// Add all of the metadata from a function.
811 void processFunctionMetadata(const Function &F);
813 /// Add all of the metadata from an instruction.
814 void processInstructionMetadata(const Instruction &I);
817 } // end namespace llvm
819 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
821 : M(M), F(F), Machine(&Machine) {}
823 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
824 bool ShouldInitializeAllMetadata)
825 : ShouldCreateStorage(M),
826 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
828 ModuleSlotTracker::~ModuleSlotTracker() = default;
830 SlotTracker *ModuleSlotTracker::getMachine() {
831 if (!ShouldCreateStorage)
834 ShouldCreateStorage = false;
836 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
837 Machine = MachineStorage.get();
841 void ModuleSlotTracker::incorporateFunction(const Function &F) {
842 // Using getMachine() may lazily create the slot tracker.
846 // Nothing to do if this is the right function already.
850 Machine->purgeFunction();
851 Machine->incorporateFunction(&F);
855 int ModuleSlotTracker::getLocalSlot(const Value *V) {
856 assert(F && "No function incorporated");
857 return Machine->getLocalSlot(V);
860 static SlotTracker *createSlotTracker(const Value *V) {
861 if (const Argument *FA = dyn_cast<Argument>(V))
862 return new SlotTracker(FA->getParent());
864 if (const Instruction *I = dyn_cast<Instruction>(V))
866 return new SlotTracker(I->getParent()->getParent());
868 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
869 return new SlotTracker(BB->getParent());
871 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
872 return new SlotTracker(GV->getParent());
874 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
875 return new SlotTracker(GA->getParent());
877 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
878 return new SlotTracker(GIF->getParent());
880 if (const Function *Func = dyn_cast<Function>(V))
881 return new SlotTracker(Func);
887 #define ST_DEBUG(X) dbgs() << X
892 // Module level constructor. Causes the contents of the Module (sans functions)
893 // to be added to the slot table.
894 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
895 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
897 // Function level constructor. Causes the contents of the Module and the one
898 // function provided to be added to the slot table.
899 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
900 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
901 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
903 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
904 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
906 inline void SlotTracker::initializeIfNeeded() {
909 TheModule = nullptr; ///< Prevent re-processing next time we're called.
912 if (TheFunction && !FunctionProcessed)
916 void SlotTracker::initializeIndexIfNeeded() {
920 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
923 // Iterate through all the global variables, functions, and global
924 // variable initializers and create slots for them.
925 void SlotTracker::processModule() {
926 ST_DEBUG("begin processModule!\n");
928 // Add all of the unnamed global variables to the value table.
929 for (const GlobalVariable &Var : TheModule->globals()) {
931 CreateModuleSlot(&Var);
932 processGlobalObjectMetadata(Var);
933 auto Attrs = Var.getAttributes();
934 if (Attrs.hasAttributes())
935 CreateAttributeSetSlot(Attrs);
938 for (const GlobalAlias &A : TheModule->aliases()) {
940 CreateModuleSlot(&A);
943 for (const GlobalIFunc &I : TheModule->ifuncs()) {
945 CreateModuleSlot(&I);
948 // Add metadata used by named metadata.
949 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
950 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
951 CreateMetadataSlot(NMD.getOperand(i));
954 for (const Function &F : *TheModule) {
956 // Add all the unnamed functions to the table.
957 CreateModuleSlot(&F);
959 if (ShouldInitializeAllMetadata)
960 processFunctionMetadata(F);
962 // Add all the function attributes to the table.
963 // FIXME: Add attributes of other objects?
964 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
965 if (FnAttrs.hasAttributes())
966 CreateAttributeSetSlot(FnAttrs);
969 ST_DEBUG("end processModule!\n");
972 // Process the arguments, basic blocks, and instructions of a function.
973 void SlotTracker::processFunction() {
974 ST_DEBUG("begin processFunction!\n");
977 // Process function metadata if it wasn't hit at the module-level.
978 if (!ShouldInitializeAllMetadata)
979 processFunctionMetadata(*TheFunction);
981 // Add all the function arguments with no names.
982 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
983 AE = TheFunction->arg_end(); AI != AE; ++AI)
985 CreateFunctionSlot(&*AI);
987 ST_DEBUG("Inserting Instructions:\n");
989 // Add all of the basic blocks and instructions with no names.
990 for (auto &BB : *TheFunction) {
992 CreateFunctionSlot(&BB);
995 if (!I.getType()->isVoidTy() && !I.hasName())
996 CreateFunctionSlot(&I);
998 // We allow direct calls to any llvm.foo function here, because the
999 // target may not be linked into the optimizer.
1000 if (const auto *Call = dyn_cast<CallBase>(&I)) {
1001 // Add all the call attributes to the table.
1002 AttributeSet Attrs = Call->getAttributes().getFnAttributes();
1003 if (Attrs.hasAttributes())
1004 CreateAttributeSetSlot(Attrs);
1009 FunctionProcessed = true;
1011 ST_DEBUG("end processFunction!\n");
1014 // Iterate through all the GUID in the index and create slots for them.
1015 void SlotTracker::processIndex() {
1016 ST_DEBUG("begin processIndex!\n");
1019 // The first block of slots are just the module ids, which start at 0 and are
1020 // assigned consecutively. Since the StringMap iteration order isn't
1021 // guaranteed, use a std::map to order by module ID before assigning slots.
1022 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1023 for (auto &ModPath : TheIndex->modulePaths())
1024 ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1025 for (auto &ModPair : ModuleIdToPathMap)
1026 CreateModulePathSlot(ModPair.second);
1028 // Start numbering the GUIDs after the module ids.
1029 GUIDNext = ModulePathNext;
1031 for (auto &GlobalList : *TheIndex)
1032 CreateGUIDSlot(GlobalList.first);
1034 // Start numbering the TypeIds after the GUIDs.
1035 TypeIdNext = GUIDNext;
1037 for (auto TidIter = TheIndex->typeIds().begin();
1038 TidIter != TheIndex->typeIds().end(); TidIter++)
1039 CreateTypeIdSlot(TidIter->second.first);
1041 ST_DEBUG("end processIndex!\n");
1044 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1045 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1046 GO.getAllMetadata(MDs);
1047 for (auto &MD : MDs)
1048 CreateMetadataSlot(MD.second);
1051 void SlotTracker::processFunctionMetadata(const Function &F) {
1052 processGlobalObjectMetadata(F);
1053 for (auto &BB : F) {
1055 processInstructionMetadata(I);
1059 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1060 // Process metadata used directly by intrinsics.
1061 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1062 if (Function *F = CI->getCalledFunction())
1063 if (F->isIntrinsic())
1064 for (auto &Op : I.operands())
1065 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1066 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1067 CreateMetadataSlot(N);
1069 // Process metadata attached to this instruction.
1070 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1071 I.getAllMetadata(MDs);
1072 for (auto &MD : MDs)
1073 CreateMetadataSlot(MD.second);
1076 /// Clean up after incorporating a function. This is the only way to get out of
1077 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1078 /// incorporation state is indicated by TheFunction != 0.
1079 void SlotTracker::purgeFunction() {
1080 ST_DEBUG("begin purgeFunction!\n");
1081 fMap.clear(); // Simply discard the function level map
1082 TheFunction = nullptr;
1083 FunctionProcessed = false;
1084 ST_DEBUG("end purgeFunction!\n");
1087 /// getGlobalSlot - Get the slot number of a global value.
1088 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1089 // Check for uninitialized state and do lazy initialization.
1090 initializeIfNeeded();
1092 // Find the value in the module map
1093 ValueMap::iterator MI = mMap.find(V);
1094 return MI == mMap.end() ? -1 : (int)MI->second;
1097 /// getMetadataSlot - Get the slot number of a MDNode.
1098 int SlotTracker::getMetadataSlot(const MDNode *N) {
1099 // Check for uninitialized state and do lazy initialization.
1100 initializeIfNeeded();
1102 // Find the MDNode in the module map
1103 mdn_iterator MI = mdnMap.find(N);
1104 return MI == mdnMap.end() ? -1 : (int)MI->second;
1107 /// getLocalSlot - Get the slot number for a value that is local to a function.
1108 int SlotTracker::getLocalSlot(const Value *V) {
1109 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1111 // Check for uninitialized state and do lazy initialization.
1112 initializeIfNeeded();
1114 ValueMap::iterator FI = fMap.find(V);
1115 return FI == fMap.end() ? -1 : (int)FI->second;
1118 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1119 // Check for uninitialized state and do lazy initialization.
1120 initializeIfNeeded();
1122 // Find the AttributeSet in the module map.
1123 as_iterator AI = asMap.find(AS);
1124 return AI == asMap.end() ? -1 : (int)AI->second;
1127 int SlotTracker::getModulePathSlot(StringRef Path) {
1128 // Check for uninitialized state and do lazy initialization.
1129 initializeIndexIfNeeded();
1131 // Find the Module path in the map
1132 auto I = ModulePathMap.find(Path);
1133 return I == ModulePathMap.end() ? -1 : (int)I->second;
1136 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1137 // Check for uninitialized state and do lazy initialization.
1138 initializeIndexIfNeeded();
1140 // Find the GUID in the map
1141 guid_iterator I = GUIDMap.find(GUID);
1142 return I == GUIDMap.end() ? -1 : (int)I->second;
1145 int SlotTracker::getTypeIdSlot(StringRef Id) {
1146 // Check for uninitialized state and do lazy initialization.
1147 initializeIndexIfNeeded();
1149 // Find the TypeId string in the map
1150 auto I = TypeIdMap.find(Id);
1151 return I == TypeIdMap.end() ? -1 : (int)I->second;
1154 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1155 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1156 assert(V && "Can't insert a null Value into SlotTracker!");
1157 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1158 assert(!V->hasName() && "Doesn't need a slot!");
1160 unsigned DestSlot = mNext++;
1163 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1165 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1166 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1167 (isa<Function>(V) ? 'F' :
1168 (isa<GlobalAlias>(V) ? 'A' :
1169 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1172 /// CreateSlot - Create a new slot for the specified value if it has no name.
1173 void SlotTracker::CreateFunctionSlot(const Value *V) {
1174 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1176 unsigned DestSlot = fNext++;
1179 // G = Global, F = Function, o = other
1180 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1181 DestSlot << " [o]\n");
1184 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1185 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1186 assert(N && "Can't insert a null Value into SlotTracker!");
1188 // Don't make slots for DIExpressions. We just print them inline everywhere.
1189 if (isa<DIExpression>(N))
1192 unsigned DestSlot = mdnNext;
1193 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1197 // Recursively add any MDNodes referenced by operands.
1198 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1199 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1200 CreateMetadataSlot(Op);
1203 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1204 assert(AS.hasAttributes() && "Doesn't need a slot!");
1206 as_iterator I = asMap.find(AS);
1207 if (I != asMap.end())
1210 unsigned DestSlot = asNext++;
1211 asMap[AS] = DestSlot;
1214 /// Create a new slot for the specified Module
1215 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1216 ModulePathMap[Path] = ModulePathNext++;
1219 /// Create a new slot for the specified GUID
1220 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1221 GUIDMap[GUID] = GUIDNext++;
1224 /// Create a new slot for the specified Id
1225 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1226 TypeIdMap[Id] = TypeIdNext++;
1229 //===----------------------------------------------------------------------===//
1230 // AsmWriter Implementation
1231 //===----------------------------------------------------------------------===//
1233 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1234 TypePrinting *TypePrinter,
1235 SlotTracker *Machine,
1236 const Module *Context);
1238 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1239 TypePrinting *TypePrinter,
1240 SlotTracker *Machine, const Module *Context,
1241 bool FromValue = false);
1243 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1244 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1245 // 'Fast' is an abbreviation for all fast-math-flags.
1249 if (FPO->hasAllowReassoc())
1251 if (FPO->hasNoNaNs())
1253 if (FPO->hasNoInfs())
1255 if (FPO->hasNoSignedZeros())
1257 if (FPO->hasAllowReciprocal())
1259 if (FPO->hasAllowContract())
1261 if (FPO->hasApproxFunc())
1266 if (const OverflowingBinaryOperator *OBO =
1267 dyn_cast<OverflowingBinaryOperator>(U)) {
1268 if (OBO->hasNoUnsignedWrap())
1270 if (OBO->hasNoSignedWrap())
1272 } else if (const PossiblyExactOperator *Div =
1273 dyn_cast<PossiblyExactOperator>(U)) {
1276 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1277 if (GEP->isInBounds())
1282 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1283 TypePrinting &TypePrinter,
1284 SlotTracker *Machine,
1285 const Module *Context) {
1286 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1287 if (CI->getType()->isIntegerTy(1)) {
1288 Out << (CI->getZExtValue() ? "true" : "false");
1291 Out << CI->getValue();
1295 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1296 const APFloat &APF = CFP->getValueAPF();
1297 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1298 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1299 // We would like to output the FP constant value in exponential notation,
1300 // but we cannot do this if doing so will lose precision. Check here to
1301 // make sure that we only output it in exponential format if we can parse
1302 // the value back and get the same value.
1305 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1306 bool isInf = APF.isInfinity();
1307 bool isNaN = APF.isNaN();
1308 if (!isInf && !isNaN) {
1309 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1310 SmallString<128> StrVal;
1311 APF.toString(StrVal, 6, 0, false);
1312 // Check to make sure that the stringized number is not some string like
1313 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1314 // that the string matches the "[-+]?[0-9]" regex.
1316 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1317 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1318 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1319 "[-+]?[0-9] regex does not match!");
1320 // Reparse stringized version!
1321 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1326 // Otherwise we could not reparse it to exactly the same value, so we must
1327 // output the string in hexadecimal format! Note that loading and storing
1328 // floating point types changes the bits of NaNs on some hosts, notably
1329 // x86, so we must not use these types.
1330 static_assert(sizeof(double) == sizeof(uint64_t),
1331 "assuming that double is 64 bits!");
1333 // Floats are represented in ASCII IR as double, convert.
1335 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1337 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1341 // Either half, or some form of long double.
1342 // These appear as a magic letter identifying the type, then a
1343 // fixed number of hex digits.
1345 APInt API = APF.bitcastToAPInt();
1346 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1348 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1350 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1353 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1355 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1357 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1359 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1361 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1363 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1365 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1367 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1370 llvm_unreachable("Unsupported floating point type");
1374 if (isa<ConstantAggregateZero>(CV)) {
1375 Out << "zeroinitializer";
1379 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1380 Out << "blockaddress(";
1381 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1384 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1390 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1391 Type *ETy = CA->getType()->getElementType();
1393 TypePrinter.print(ETy, Out);
1395 WriteAsOperandInternal(Out, CA->getOperand(0),
1396 &TypePrinter, Machine,
1398 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1400 TypePrinter.print(ETy, Out);
1402 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1409 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1410 // As a special case, print the array as a string if it is an array of
1411 // i8 with ConstantInt values.
1412 if (CA->isString()) {
1414 printEscapedString(CA->getAsString(), Out);
1419 Type *ETy = CA->getType()->getElementType();
1421 TypePrinter.print(ETy, Out);
1423 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1424 &TypePrinter, Machine,
1426 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1428 TypePrinter.print(ETy, Out);
1430 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1437 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1438 if (CS->getType()->isPacked())
1441 unsigned N = CS->getNumOperands();
1444 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1447 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1450 for (unsigned i = 1; i < N; i++) {
1452 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1455 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1462 if (CS->getType()->isPacked())
1467 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1468 Type *ETy = CV->getType()->getVectorElementType();
1470 TypePrinter.print(ETy, Out);
1472 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1474 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1476 TypePrinter.print(ETy, Out);
1478 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1485 if (isa<ConstantPointerNull>(CV)) {
1490 if (isa<ConstantTokenNone>(CV)) {
1495 if (isa<UndefValue>(CV)) {
1500 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1501 Out << CE->getOpcodeName();
1502 WriteOptimizationInfo(Out, CE);
1503 if (CE->isCompare())
1504 Out << ' ' << CmpInst::getPredicateName(
1505 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1508 Optional<unsigned> InRangeOp;
1509 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1510 TypePrinter.print(GEP->getSourceElementType(), Out);
1512 InRangeOp = GEP->getInRangeIndex();
1517 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1518 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1520 TypePrinter.print((*OI)->getType(), Out);
1522 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1523 if (OI+1 != CE->op_end())
1527 if (CE->hasIndices()) {
1528 ArrayRef<unsigned> Indices = CE->getIndices();
1529 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1530 Out << ", " << Indices[i];
1535 TypePrinter.print(CE->getType(), Out);
1542 Out << "<placeholder or erroneous Constant>";
1545 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1546 TypePrinting *TypePrinter, SlotTracker *Machine,
1547 const Module *Context) {
1549 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1550 const Metadata *MD = Node->getOperand(mi);
1553 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1554 Value *V = MDV->getValue();
1555 TypePrinter->print(V->getType(), Out);
1557 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1559 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1570 struct FieldSeparator {
1574 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1577 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1582 return OS << FS.Sep;
1585 struct MDFieldPrinter {
1588 TypePrinting *TypePrinter = nullptr;
1589 SlotTracker *Machine = nullptr;
1590 const Module *Context = nullptr;
1592 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1593 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1594 SlotTracker *Machine, const Module *Context)
1595 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1598 void printTag(const DINode *N);
1599 void printMacinfoType(const DIMacroNode *N);
1600 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1601 void printString(StringRef Name, StringRef Value,
1602 bool ShouldSkipEmpty = true);
1603 void printMetadata(StringRef Name, const Metadata *MD,
1604 bool ShouldSkipNull = true);
1605 template <class IntTy>
1606 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1607 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1608 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1609 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1610 template <class IntTy, class Stringifier>
1611 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1612 bool ShouldSkipZero = true);
1613 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1614 void printNameTableKind(StringRef Name,
1615 DICompileUnit::DebugNameTableKind NTK);
1618 } // end anonymous namespace
1620 void MDFieldPrinter::printTag(const DINode *N) {
1621 Out << FS << "tag: ";
1622 auto Tag = dwarf::TagString(N->getTag());
1629 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1630 Out << FS << "type: ";
1631 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1635 Out << N->getMacinfoType();
1638 void MDFieldPrinter::printChecksum(
1639 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1640 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1641 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1644 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1645 bool ShouldSkipEmpty) {
1646 if (ShouldSkipEmpty && Value.empty())
1649 Out << FS << Name << ": \"";
1650 printEscapedString(Value, Out);
1654 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1655 TypePrinting *TypePrinter,
1656 SlotTracker *Machine,
1657 const Module *Context) {
1662 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1665 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1666 bool ShouldSkipNull) {
1667 if (ShouldSkipNull && !MD)
1670 Out << FS << Name << ": ";
1671 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1674 template <class IntTy>
1675 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1676 if (ShouldSkipZero && !Int)
1679 Out << FS << Name << ": " << Int;
1682 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1683 Optional<bool> Default) {
1684 if (Default && Value == *Default)
1686 Out << FS << Name << ": " << (Value ? "true" : "false");
1689 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1693 Out << FS << Name << ": ";
1695 SmallVector<DINode::DIFlags, 8> SplitFlags;
1696 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1698 FieldSeparator FlagsFS(" | ");
1699 for (auto F : SplitFlags) {
1700 auto StringF = DINode::getFlagString(F);
1701 assert(!StringF.empty() && "Expected valid flag");
1702 Out << FlagsFS << StringF;
1704 if (Extra || SplitFlags.empty())
1705 Out << FlagsFS << Extra;
1708 void MDFieldPrinter::printDISPFlags(StringRef Name,
1709 DISubprogram::DISPFlags Flags) {
1710 // Always print this field, because no flags in the IR at all will be
1711 // interpreted as old-style isDefinition: true.
1712 Out << FS << Name << ": ";
1719 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1720 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1722 FieldSeparator FlagsFS(" | ");
1723 for (auto F : SplitFlags) {
1724 auto StringF = DISubprogram::getFlagString(F);
1725 assert(!StringF.empty() && "Expected valid flag");
1726 Out << FlagsFS << StringF;
1728 if (Extra || SplitFlags.empty())
1729 Out << FlagsFS << Extra;
1732 void MDFieldPrinter::printEmissionKind(StringRef Name,
1733 DICompileUnit::DebugEmissionKind EK) {
1734 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1737 void MDFieldPrinter::printNameTableKind(StringRef Name,
1738 DICompileUnit::DebugNameTableKind NTK) {
1739 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1741 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1744 template <class IntTy, class Stringifier>
1745 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1746 Stringifier toString, bool ShouldSkipZero) {
1750 Out << FS << Name << ": ";
1751 auto S = toString(Value);
1758 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1759 TypePrinting *TypePrinter, SlotTracker *Machine,
1760 const Module *Context) {
1761 Out << "!GenericDINode(";
1762 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1763 Printer.printTag(N);
1764 Printer.printString("header", N->getHeader());
1765 if (N->getNumDwarfOperands()) {
1766 Out << Printer.FS << "operands: {";
1768 for (auto &I : N->dwarf_operands()) {
1770 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1777 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1778 TypePrinting *TypePrinter, SlotTracker *Machine,
1779 const Module *Context) {
1780 Out << "!DILocation(";
1781 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1782 // Always output the line, since 0 is a relevant and important value for it.
1783 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1784 Printer.printInt("column", DL->getColumn());
1785 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1786 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1787 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1788 /* Default */ false);
1792 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1793 TypePrinting *TypePrinter, SlotTracker *Machine,
1794 const Module *Context) {
1795 Out << "!DISubrange(";
1796 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1797 if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1798 Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1800 Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
1801 /*ShouldSkipNull */ false);
1802 Printer.printInt("lowerBound", N->getLowerBound());
1806 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1807 TypePrinting *, SlotTracker *, const Module *) {
1808 Out << "!DIEnumerator(";
1809 MDFieldPrinter Printer(Out);
1810 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1811 if (N->isUnsigned()) {
1812 auto Value = static_cast<uint64_t>(N->getValue());
1813 Printer.printInt("value", Value, /* ShouldSkipZero */ false);
1814 Printer.printBool("isUnsigned", true);
1816 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1821 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1822 TypePrinting *, SlotTracker *, const Module *) {
1823 Out << "!DIBasicType(";
1824 MDFieldPrinter Printer(Out);
1825 if (N->getTag() != dwarf::DW_TAG_base_type)
1826 Printer.printTag(N);
1827 Printer.printString("name", N->getName());
1828 Printer.printInt("size", N->getSizeInBits());
1829 Printer.printInt("align", N->getAlignInBits());
1830 Printer.printDwarfEnum("encoding", N->getEncoding(),
1831 dwarf::AttributeEncodingString);
1832 Printer.printDIFlags("flags", N->getFlags());
1836 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1837 TypePrinting *TypePrinter, SlotTracker *Machine,
1838 const Module *Context) {
1839 Out << "!DIDerivedType(";
1840 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1841 Printer.printTag(N);
1842 Printer.printString("name", N->getName());
1843 Printer.printMetadata("scope", N->getRawScope());
1844 Printer.printMetadata("file", N->getRawFile());
1845 Printer.printInt("line", N->getLine());
1846 Printer.printMetadata("baseType", N->getRawBaseType(),
1847 /* ShouldSkipNull */ false);
1848 Printer.printInt("size", N->getSizeInBits());
1849 Printer.printInt("align", N->getAlignInBits());
1850 Printer.printInt("offset", N->getOffsetInBits());
1851 Printer.printDIFlags("flags", N->getFlags());
1852 Printer.printMetadata("extraData", N->getRawExtraData());
1853 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1854 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1855 /* ShouldSkipZero */ false);
1859 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1860 TypePrinting *TypePrinter,
1861 SlotTracker *Machine, const Module *Context) {
1862 Out << "!DICompositeType(";
1863 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1864 Printer.printTag(N);
1865 Printer.printString("name", N->getName());
1866 Printer.printMetadata("scope", N->getRawScope());
1867 Printer.printMetadata("file", N->getRawFile());
1868 Printer.printInt("line", N->getLine());
1869 Printer.printMetadata("baseType", N->getRawBaseType());
1870 Printer.printInt("size", N->getSizeInBits());
1871 Printer.printInt("align", N->getAlignInBits());
1872 Printer.printInt("offset", N->getOffsetInBits());
1873 Printer.printDIFlags("flags", N->getFlags());
1874 Printer.printMetadata("elements", N->getRawElements());
1875 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1876 dwarf::LanguageString);
1877 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1878 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1879 Printer.printString("identifier", N->getIdentifier());
1880 Printer.printMetadata("discriminator", N->getRawDiscriminator());
1884 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1885 TypePrinting *TypePrinter,
1886 SlotTracker *Machine, const Module *Context) {
1887 Out << "!DISubroutineType(";
1888 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1889 Printer.printDIFlags("flags", N->getFlags());
1890 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1891 Printer.printMetadata("types", N->getRawTypeArray(),
1892 /* ShouldSkipNull */ false);
1896 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1897 SlotTracker *, const Module *) {
1899 MDFieldPrinter Printer(Out);
1900 Printer.printString("filename", N->getFilename(),
1901 /* ShouldSkipEmpty */ false);
1902 Printer.printString("directory", N->getDirectory(),
1903 /* ShouldSkipEmpty */ false);
1904 // Print all values for checksum together, or not at all.
1905 if (N->getChecksum())
1906 Printer.printChecksum(*N->getChecksum());
1907 Printer.printString("source", N->getSource().getValueOr(StringRef()),
1908 /* ShouldSkipEmpty */ true);
1912 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1913 TypePrinting *TypePrinter, SlotTracker *Machine,
1914 const Module *Context) {
1915 Out << "!DICompileUnit(";
1916 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1917 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1918 dwarf::LanguageString, /* ShouldSkipZero */ false);
1919 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1920 Printer.printString("producer", N->getProducer());
1921 Printer.printBool("isOptimized", N->isOptimized());
1922 Printer.printString("flags", N->getFlags());
1923 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1924 /* ShouldSkipZero */ false);
1925 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1926 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1927 Printer.printMetadata("enums", N->getRawEnumTypes());
1928 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1929 Printer.printMetadata("globals", N->getRawGlobalVariables());
1930 Printer.printMetadata("imports", N->getRawImportedEntities());
1931 Printer.printMetadata("macros", N->getRawMacros());
1932 Printer.printInt("dwoId", N->getDWOId());
1933 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1934 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1936 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
1937 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
1941 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1942 TypePrinting *TypePrinter, SlotTracker *Machine,
1943 const Module *Context) {
1944 Out << "!DISubprogram(";
1945 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1946 Printer.printString("name", N->getName());
1947 Printer.printString("linkageName", N->getLinkageName());
1948 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1949 Printer.printMetadata("file", N->getRawFile());
1950 Printer.printInt("line", N->getLine());
1951 Printer.printMetadata("type", N->getRawType());
1952 Printer.printInt("scopeLine", N->getScopeLine());
1953 Printer.printMetadata("containingType", N->getRawContainingType());
1954 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1955 N->getVirtualIndex() != 0)
1956 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1957 Printer.printInt("thisAdjustment", N->getThisAdjustment());
1958 Printer.printDIFlags("flags", N->getFlags());
1959 Printer.printDISPFlags("spFlags", N->getSPFlags());
1960 Printer.printMetadata("unit", N->getRawUnit());
1961 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1962 Printer.printMetadata("declaration", N->getRawDeclaration());
1963 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
1964 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1968 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1969 TypePrinting *TypePrinter, SlotTracker *Machine,
1970 const Module *Context) {
1971 Out << "!DILexicalBlock(";
1972 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1973 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1974 Printer.printMetadata("file", N->getRawFile());
1975 Printer.printInt("line", N->getLine());
1976 Printer.printInt("column", N->getColumn());
1980 static void writeDILexicalBlockFile(raw_ostream &Out,
1981 const DILexicalBlockFile *N,
1982 TypePrinting *TypePrinter,
1983 SlotTracker *Machine,
1984 const Module *Context) {
1985 Out << "!DILexicalBlockFile(";
1986 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1987 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1988 Printer.printMetadata("file", N->getRawFile());
1989 Printer.printInt("discriminator", N->getDiscriminator(),
1990 /* ShouldSkipZero */ false);
1994 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1995 TypePrinting *TypePrinter, SlotTracker *Machine,
1996 const Module *Context) {
1997 Out << "!DINamespace(";
1998 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1999 Printer.printString("name", N->getName());
2000 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2001 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2005 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2006 TypePrinting *TypePrinter, SlotTracker *Machine,
2007 const Module *Context) {
2009 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2010 Printer.printMacinfoType(N);
2011 Printer.printInt("line", N->getLine());
2012 Printer.printString("name", N->getName());
2013 Printer.printString("value", N->getValue());
2017 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2018 TypePrinting *TypePrinter, SlotTracker *Machine,
2019 const Module *Context) {
2020 Out << "!DIMacroFile(";
2021 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2022 Printer.printInt("line", N->getLine());
2023 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2024 Printer.printMetadata("nodes", N->getRawElements());
2028 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2029 TypePrinting *TypePrinter, SlotTracker *Machine,
2030 const Module *Context) {
2031 Out << "!DIModule(";
2032 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2033 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2034 Printer.printString("name", N->getName());
2035 Printer.printString("configMacros", N->getConfigurationMacros());
2036 Printer.printString("includePath", N->getIncludePath());
2037 Printer.printString("isysroot", N->getISysRoot());
2042 static void writeDITemplateTypeParameter(raw_ostream &Out,
2043 const DITemplateTypeParameter *N,
2044 TypePrinting *TypePrinter,
2045 SlotTracker *Machine,
2046 const Module *Context) {
2047 Out << "!DITemplateTypeParameter(";
2048 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2049 Printer.printString("name", N->getName());
2050 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2054 static void writeDITemplateValueParameter(raw_ostream &Out,
2055 const DITemplateValueParameter *N,
2056 TypePrinting *TypePrinter,
2057 SlotTracker *Machine,
2058 const Module *Context) {
2059 Out << "!DITemplateValueParameter(";
2060 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2061 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2062 Printer.printTag(N);
2063 Printer.printString("name", N->getName());
2064 Printer.printMetadata("type", N->getRawType());
2065 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2069 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2070 TypePrinting *TypePrinter,
2071 SlotTracker *Machine, const Module *Context) {
2072 Out << "!DIGlobalVariable(";
2073 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2074 Printer.printString("name", N->getName());
2075 Printer.printString("linkageName", N->getLinkageName());
2076 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2077 Printer.printMetadata("file", N->getRawFile());
2078 Printer.printInt("line", N->getLine());
2079 Printer.printMetadata("type", N->getRawType());
2080 Printer.printBool("isLocal", N->isLocalToUnit());
2081 Printer.printBool("isDefinition", N->isDefinition());
2082 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2083 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2084 Printer.printInt("align", N->getAlignInBits());
2088 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2089 TypePrinting *TypePrinter,
2090 SlotTracker *Machine, const Module *Context) {
2091 Out << "!DILocalVariable(";
2092 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2093 Printer.printString("name", N->getName());
2094 Printer.printInt("arg", N->getArg());
2095 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2096 Printer.printMetadata("file", N->getRawFile());
2097 Printer.printInt("line", N->getLine());
2098 Printer.printMetadata("type", N->getRawType());
2099 Printer.printDIFlags("flags", N->getFlags());
2100 Printer.printInt("align", N->getAlignInBits());
2104 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2105 TypePrinting *TypePrinter,
2106 SlotTracker *Machine, const Module *Context) {
2108 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2109 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2110 Printer.printString("name", N->getName());
2111 Printer.printMetadata("file", N->getRawFile());
2112 Printer.printInt("line", N->getLine());
2116 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2117 TypePrinting *TypePrinter, SlotTracker *Machine,
2118 const Module *Context) {
2119 Out << "!DIExpression(";
2122 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
2123 auto OpStr = dwarf::OperationEncodingString(I->getOp());
2124 assert(!OpStr.empty() && "Expected valid opcode");
2127 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2128 Out << FS << I->getArg(A);
2131 for (const auto &I : N->getElements())
2137 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2138 const DIGlobalVariableExpression *N,
2139 TypePrinting *TypePrinter,
2140 SlotTracker *Machine,
2141 const Module *Context) {
2142 Out << "!DIGlobalVariableExpression(";
2143 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2144 Printer.printMetadata("var", N->getVariable());
2145 Printer.printMetadata("expr", N->getExpression());
2149 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2150 TypePrinting *TypePrinter, SlotTracker *Machine,
2151 const Module *Context) {
2152 Out << "!DIObjCProperty(";
2153 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2154 Printer.printString("name", N->getName());
2155 Printer.printMetadata("file", N->getRawFile());
2156 Printer.printInt("line", N->getLine());
2157 Printer.printString("setter", N->getSetterName());
2158 Printer.printString("getter", N->getGetterName());
2159 Printer.printInt("attributes", N->getAttributes());
2160 Printer.printMetadata("type", N->getRawType());
2164 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2165 TypePrinting *TypePrinter,
2166 SlotTracker *Machine, const Module *Context) {
2167 Out << "!DIImportedEntity(";
2168 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2169 Printer.printTag(N);
2170 Printer.printString("name", N->getName());
2171 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2172 Printer.printMetadata("entity", N->getRawEntity());
2173 Printer.printMetadata("file", N->getRawFile());
2174 Printer.printInt("line", N->getLine());
2178 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2179 TypePrinting *TypePrinter,
2180 SlotTracker *Machine,
2181 const Module *Context) {
2182 if (Node->isDistinct())
2184 else if (Node->isTemporary())
2185 Out << "<temporary!> "; // Handle broken code.
2187 switch (Node->getMetadataID()) {
2189 llvm_unreachable("Expected uniquable MDNode");
2190 #define HANDLE_MDNODE_LEAF(CLASS) \
2191 case Metadata::CLASS##Kind: \
2192 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
2194 #include "llvm/IR/Metadata.def"
2198 // Full implementation of printing a Value as an operand with support for
2199 // TypePrinting, etc.
2200 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2201 TypePrinting *TypePrinter,
2202 SlotTracker *Machine,
2203 const Module *Context) {
2205 PrintLLVMName(Out, V);
2209 const Constant *CV = dyn_cast<Constant>(V);
2210 if (CV && !isa<GlobalValue>(CV)) {
2211 assert(TypePrinter && "Constants require TypePrinting!");
2212 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2216 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2218 if (IA->hasSideEffects())
2219 Out << "sideeffect ";
2220 if (IA->isAlignStack())
2221 Out << "alignstack ";
2222 // We don't emit the AD_ATT dialect as it's the assumed default.
2223 if (IA->getDialect() == InlineAsm::AD_Intel)
2224 Out << "inteldialect ";
2226 printEscapedString(IA->getAsmString(), Out);
2228 printEscapedString(IA->getConstraintString(), Out);
2233 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2234 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2235 Context, /* FromValue */ true);
2241 // If we have a SlotTracker, use it.
2243 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2244 Slot = Machine->getGlobalSlot(GV);
2247 Slot = Machine->getLocalSlot(V);
2249 // If the local value didn't succeed, then we may be referring to a value
2250 // from a different function. Translate it, as this can happen when using
2251 // address of blocks.
2253 if ((Machine = createSlotTracker(V))) {
2254 Slot = Machine->getLocalSlot(V);
2258 } else if ((Machine = createSlotTracker(V))) {
2259 // Otherwise, create one to get the # and then destroy it.
2260 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2261 Slot = Machine->getGlobalSlot(GV);
2264 Slot = Machine->getLocalSlot(V);
2273 Out << Prefix << Slot;
2278 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2279 TypePrinting *TypePrinter,
2280 SlotTracker *Machine, const Module *Context,
2282 // Write DIExpressions inline when used as a value. Improves readability of
2283 // debug info intrinsics.
2284 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2285 writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2289 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2290 std::unique_ptr<SlotTracker> MachineStorage;
2292 MachineStorage = make_unique<SlotTracker>(Context);
2293 Machine = MachineStorage.get();
2295 int Slot = Machine->getMetadataSlot(N);
2297 if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2298 writeDILocation(Out, Loc, TypePrinter, Machine, Context);
2301 // Give the pointer value instead of "badref", since this comes up all
2302 // the time when debugging.
2303 Out << "<" << N << ">";
2309 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2311 printEscapedString(MDS->getString(), Out);
2316 auto *V = cast<ValueAsMetadata>(MD);
2317 assert(TypePrinter && "TypePrinter required for metadata values");
2318 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2319 "Unexpected function-local metadata outside of value argument");
2321 TypePrinter->print(V->getValue()->getType(), Out);
2323 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2328 class AssemblyWriter {
2329 formatted_raw_ostream &Out;
2330 const Module *TheModule = nullptr;
2331 const ModuleSummaryIndex *TheIndex = nullptr;
2332 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2333 SlotTracker &Machine;
2334 TypePrinting TypePrinter;
2335 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2336 SetVector<const Comdat *> Comdats;
2338 bool ShouldPreserveUseListOrder;
2339 UseListOrderStack UseListOrders;
2340 SmallVector<StringRef, 8> MDNames;
2341 /// Synchronization scope names registered with LLVMContext.
2342 SmallVector<StringRef, 8> SSNs;
2343 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2346 /// Construct an AssemblyWriter with an external SlotTracker
2347 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2348 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2349 bool ShouldPreserveUseListOrder = false);
2351 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2352 const ModuleSummaryIndex *Index, bool IsForDebug);
2354 void printMDNodeBody(const MDNode *MD);
2355 void printNamedMDNode(const NamedMDNode *NMD);
2357 void printModule(const Module *M);
2359 void writeOperand(const Value *Op, bool PrintType);
2360 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2361 void writeOperandBundles(const CallBase *Call);
2362 void writeSyncScope(const LLVMContext &Context,
2363 SyncScope::ID SSID);
2364 void writeAtomic(const LLVMContext &Context,
2365 AtomicOrdering Ordering,
2366 SyncScope::ID SSID);
2367 void writeAtomicCmpXchg(const LLVMContext &Context,
2368 AtomicOrdering SuccessOrdering,
2369 AtomicOrdering FailureOrdering,
2370 SyncScope::ID SSID);
2372 void writeAllMDNodes();
2373 void writeMDNode(unsigned Slot, const MDNode *Node);
2374 void writeAllAttributeGroups();
2376 void printTypeIdentities();
2377 void printGlobal(const GlobalVariable *GV);
2378 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2379 void printComdat(const Comdat *C);
2380 void printFunction(const Function *F);
2381 void printArgument(const Argument *FA, AttributeSet Attrs);
2382 void printBasicBlock(const BasicBlock *BB);
2383 void printInstructionLine(const Instruction &I);
2384 void printInstruction(const Instruction &I);
2386 void printUseListOrder(const UseListOrder &Order);
2387 void printUseLists(const Function *F);
2389 void printModuleSummaryIndex();
2390 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2391 void printSummary(const GlobalValueSummary &Summary);
2392 void printAliasSummary(const AliasSummary *AS);
2393 void printGlobalVarSummary(const GlobalVarSummary *GS);
2394 void printFunctionSummary(const FunctionSummary *FS);
2395 void printTypeIdSummary(const TypeIdSummary &TIS);
2396 void printTypeTestResolution(const TypeTestResolution &TTRes);
2397 void printArgs(const std::vector<uint64_t> &Args);
2398 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2399 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2400 void printVFuncId(const FunctionSummary::VFuncId VFId);
2402 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2405 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2409 /// Print out metadata attachments.
2410 void printMetadataAttachments(
2411 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2412 StringRef Separator);
2414 // printInfoComment - Print a little comment after the instruction indicating
2415 // which slot it occupies.
2416 void printInfoComment(const Value &V);
2418 // printGCRelocateComment - print comment after call to the gc.relocate
2419 // intrinsic indicating base and derived pointer names.
2420 void printGCRelocateComment(const GCRelocateInst &Relocate);
2423 } // end anonymous namespace
2425 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2426 const Module *M, AssemblyAnnotationWriter *AAW,
2427 bool IsForDebug, bool ShouldPreserveUseListOrder)
2428 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2429 IsForDebug(IsForDebug),
2430 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2433 for (const GlobalObject &GO : TheModule->global_objects())
2434 if (const Comdat *C = GO.getComdat())
2438 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2439 const ModuleSummaryIndex *Index, bool IsForDebug)
2440 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2441 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2443 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2445 Out << "<null operand!>";
2449 TypePrinter.print(Operand->getType(), Out);
2452 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2455 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2456 SyncScope::ID SSID) {
2458 case SyncScope::System: {
2463 Context.getSyncScopeNames(SSNs);
2465 Out << " syncscope(\"";
2466 printEscapedString(SSNs[SSID], Out);
2473 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2474 AtomicOrdering Ordering,
2475 SyncScope::ID SSID) {
2476 if (Ordering == AtomicOrdering::NotAtomic)
2479 writeSyncScope(Context, SSID);
2480 Out << " " << toIRString(Ordering);
2483 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2484 AtomicOrdering SuccessOrdering,
2485 AtomicOrdering FailureOrdering,
2486 SyncScope::ID SSID) {
2487 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2488 FailureOrdering != AtomicOrdering::NotAtomic);
2490 writeSyncScope(Context, SSID);
2491 Out << " " << toIRString(SuccessOrdering);
2492 Out << " " << toIRString(FailureOrdering);
2495 void AssemblyWriter::writeParamOperand(const Value *Operand,
2496 AttributeSet Attrs) {
2498 Out << "<null operand!>";
2503 TypePrinter.print(Operand->getType(), Out);
2504 // Print parameter attributes list
2505 if (Attrs.hasAttributes())
2506 Out << ' ' << Attrs.getAsString();
2508 // Print the operand
2509 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2512 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2513 if (!Call->hasOperandBundles())
2518 bool FirstBundle = true;
2519 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2520 OperandBundleUse BU = Call->getOperandBundleAt(i);
2524 FirstBundle = false;
2527 printEscapedString(BU.getTagName(), Out);
2532 bool FirstInput = true;
2533 for (const auto &Input : BU.Inputs) {
2538 TypePrinter.print(Input->getType(), Out);
2540 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2549 void AssemblyWriter::printModule(const Module *M) {
2550 Machine.initializeIfNeeded();
2552 if (ShouldPreserveUseListOrder)
2553 UseListOrders = predictUseListOrder(M);
2555 if (!M->getModuleIdentifier().empty() &&
2556 // Don't print the ID if it will start a new line (which would
2557 // require a comment char before it).
2558 M->getModuleIdentifier().find('\n') == std::string::npos)
2559 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2561 if (!M->getSourceFileName().empty()) {
2562 Out << "source_filename = \"";
2563 printEscapedString(M->getSourceFileName(), Out);
2567 const std::string &DL = M->getDataLayoutStr();
2569 Out << "target datalayout = \"" << DL << "\"\n";
2570 if (!M->getTargetTriple().empty())
2571 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2573 if (!M->getModuleInlineAsm().empty()) {
2576 // Split the string into lines, to make it easier to read the .ll file.
2577 StringRef Asm = M->getModuleInlineAsm();
2580 std::tie(Front, Asm) = Asm.split('\n');
2582 // We found a newline, print the portion of the asm string from the
2583 // last newline up to this newline.
2584 Out << "module asm \"";
2585 printEscapedString(Front, Out);
2587 } while (!Asm.empty());
2590 printTypeIdentities();
2592 // Output all comdats.
2593 if (!Comdats.empty())
2595 for (const Comdat *C : Comdats) {
2597 if (C != Comdats.back())
2601 // Output all globals.
2602 if (!M->global_empty()) Out << '\n';
2603 for (const GlobalVariable &GV : M->globals()) {
2604 printGlobal(&GV); Out << '\n';
2607 // Output all aliases.
2608 if (!M->alias_empty()) Out << "\n";
2609 for (const GlobalAlias &GA : M->aliases())
2610 printIndirectSymbol(&GA);
2612 // Output all ifuncs.
2613 if (!M->ifunc_empty()) Out << "\n";
2614 for (const GlobalIFunc &GI : M->ifuncs())
2615 printIndirectSymbol(&GI);
2617 // Output global use-lists.
2618 printUseLists(nullptr);
2620 // Output all of the functions.
2621 for (const Function &F : *M)
2623 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2625 // Output all attribute groups.
2626 if (!Machine.as_empty()) {
2628 writeAllAttributeGroups();
2631 // Output named metadata.
2632 if (!M->named_metadata_empty()) Out << '\n';
2634 for (const NamedMDNode &Node : M->named_metadata())
2635 printNamedMDNode(&Node);
2638 if (!Machine.mdn_empty()) {
2644 void AssemblyWriter::printModuleSummaryIndex() {
2646 Machine.initializeIndexIfNeeded();
2650 // Print module path entries. To print in order, add paths to a vector
2651 // indexed by module slot.
2652 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2653 std::string RegularLTOModuleName = "[Regular LTO]";
2654 moduleVec.resize(TheIndex->modulePaths().size());
2655 for (auto &ModPath : TheIndex->modulePaths())
2656 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2657 // A module id of -1 is a special entry for a regular LTO module created
2658 // during the thin link.
2659 ModPath.second.first == -1u ? RegularLTOModuleName
2660 : (std::string)ModPath.first(),
2661 ModPath.second.second);
2664 for (auto &ModPair : moduleVec) {
2665 Out << "^" << i++ << " = module: (";
2667 printEscapedString(ModPair.first, Out);
2668 Out << "\", hash: (";
2670 for (auto Hash : ModPair.second)
2675 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2676 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2677 for (auto &GlobalList : *TheIndex) {
2678 auto GUID = GlobalList.first;
2679 for (auto &Summary : GlobalList.second.SummaryList)
2680 SummaryToGUIDMap[Summary.get()] = GUID;
2683 // Print the global value summary entries.
2684 for (auto &GlobalList : *TheIndex) {
2685 auto GUID = GlobalList.first;
2686 auto VI = TheIndex->getValueInfo(GlobalList);
2687 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2690 // Print the TypeIdMap entries.
2691 for (auto TidIter = TheIndex->typeIds().begin();
2692 TidIter != TheIndex->typeIds().end(); TidIter++) {
2693 Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2694 << " = typeid: (name: \"" << TidIter->second.first << "\"";
2695 printTypeIdSummary(TidIter->second.second);
2696 Out << ") ; guid = " << TidIter->first << "\n";
2701 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2703 case WholeProgramDevirtResolution::Indir:
2705 case WholeProgramDevirtResolution::SingleImpl:
2706 return "singleImpl";
2707 case WholeProgramDevirtResolution::BranchFunnel:
2708 return "branchFunnel";
2710 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2713 static const char *getWholeProgDevirtResByArgKindName(
2714 WholeProgramDevirtResolution::ByArg::Kind K) {
2716 case WholeProgramDevirtResolution::ByArg::Indir:
2718 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2719 return "uniformRetVal";
2720 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2721 return "uniqueRetVal";
2722 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2723 return "virtualConstProp";
2725 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2728 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2730 case TypeTestResolution::Unsat:
2732 case TypeTestResolution::ByteArray:
2734 case TypeTestResolution::Inline:
2736 case TypeTestResolution::Single:
2738 case TypeTestResolution::AllOnes:
2741 llvm_unreachable("invalid TypeTestResolution kind");
2744 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2745 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2746 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2748 // The following fields are only used if the target does not support the use
2749 // of absolute symbols to store constants. Print only if non-zero.
2750 if (TTRes.AlignLog2)
2751 Out << ", alignLog2: " << TTRes.AlignLog2;
2753 Out << ", sizeM1: " << TTRes.SizeM1;
2755 // BitMask is uint8_t which causes it to print the corresponding char.
2756 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2757 if (TTRes.InlineBits)
2758 Out << ", inlineBits: " << TTRes.InlineBits;
2763 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2764 Out << ", summary: (";
2765 printTypeTestResolution(TIS.TTRes);
2766 if (!TIS.WPDRes.empty()) {
2767 Out << ", wpdResolutions: (";
2769 for (auto &WPDRes : TIS.WPDRes) {
2771 Out << "(offset: " << WPDRes.first << ", ";
2772 printWPDRes(WPDRes.second);
2780 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2783 for (auto arg : Args) {
2790 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2791 Out << "wpdRes: (kind: ";
2792 Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2794 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2795 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2797 if (!WPDRes.ResByArg.empty()) {
2798 Out << ", resByArg: (";
2800 for (auto &ResByArg : WPDRes.ResByArg) {
2802 printArgs(ResByArg.first);
2803 Out << ", byArg: (kind: ";
2804 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2805 if (ResByArg.second.TheKind ==
2806 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2807 ResByArg.second.TheKind ==
2808 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2809 Out << ", info: " << ResByArg.second.Info;
2811 // The following fields are only used if the target does not support the
2812 // use of absolute symbols to store constants. Print only if non-zero.
2813 if (ResByArg.second.Byte || ResByArg.second.Bit)
2814 Out << ", byte: " << ResByArg.second.Byte
2815 << ", bit: " << ResByArg.second.Bit;
2824 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2826 case GlobalValueSummary::AliasKind:
2828 case GlobalValueSummary::FunctionKind:
2830 case GlobalValueSummary::GlobalVarKind:
2833 llvm_unreachable("invalid summary kind");
2836 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2837 Out << ", aliasee: ";
2838 // The indexes emitted for distributed backends may not include the
2839 // aliasee summary (only if it is being imported directly). Handle
2840 // that case by just emitting "null" as the aliasee.
2841 if (AS->hasAliasee())
2842 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2847 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2848 Out << ", varFlags: (readonly: " << GS->VarFlags.ReadOnly << ")";
2851 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2853 case GlobalValue::ExternalLinkage:
2855 case GlobalValue::PrivateLinkage:
2857 case GlobalValue::InternalLinkage:
2859 case GlobalValue::LinkOnceAnyLinkage:
2861 case GlobalValue::LinkOnceODRLinkage:
2862 return "linkonce_odr";
2863 case GlobalValue::WeakAnyLinkage:
2865 case GlobalValue::WeakODRLinkage:
2867 case GlobalValue::CommonLinkage:
2869 case GlobalValue::AppendingLinkage:
2871 case GlobalValue::ExternalWeakLinkage:
2872 return "extern_weak";
2873 case GlobalValue::AvailableExternallyLinkage:
2874 return "available_externally";
2876 llvm_unreachable("invalid linkage");
2879 // When printing the linkage types in IR where the ExternalLinkage is
2880 // not printed, and other linkage types are expected to be printed with
2881 // a space after the name.
2882 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2883 if (LT == GlobalValue::ExternalLinkage)
2885 return getLinkageName(LT) + " ";
2888 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2889 Out << ", insts: " << FS->instCount();
2891 FunctionSummary::FFlags FFlags = FS->fflags();
2892 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2893 FFlags.ReturnDoesNotAlias) {
2894 Out << ", funcFlags: (";
2895 Out << "readNone: " << FFlags.ReadNone;
2896 Out << ", readOnly: " << FFlags.ReadOnly;
2897 Out << ", noRecurse: " << FFlags.NoRecurse;
2898 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2899 Out << ", noInline: " << FFlags.NoInline;
2902 if (!FS->calls().empty()) {
2903 Out << ", calls: (";
2905 for (auto &Call : FS->calls()) {
2907 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2908 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2909 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2910 else if (Call.second.RelBlockFreq)
2911 Out << ", relbf: " << Call.second.RelBlockFreq;
2917 if (const auto *TIdInfo = FS->getTypeIdInfo())
2918 printTypeIdInfo(*TIdInfo);
2921 void AssemblyWriter::printTypeIdInfo(
2922 const FunctionSummary::TypeIdInfo &TIDInfo) {
2923 Out << ", typeIdInfo: (";
2924 FieldSeparator TIDFS;
2925 if (!TIDInfo.TypeTests.empty()) {
2927 Out << "typeTests: (";
2929 for (auto &GUID : TIDInfo.TypeTests) {
2930 auto TidIter = TheIndex->typeIds().equal_range(GUID);
2931 if (TidIter.first == TidIter.second) {
2936 // Print all type id that correspond to this GUID.
2937 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2939 auto Slot = Machine.getTypeIdSlot(It->second.first);
2946 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2948 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2950 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2952 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2954 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2956 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2957 "typeTestAssumeConstVCalls");
2959 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2961 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2962 "typeCheckedLoadConstVCalls");
2967 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
2968 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
2969 if (TidIter.first == TidIter.second) {
2970 Out << "vFuncId: (";
2971 Out << "guid: " << VFId.GUID;
2972 Out << ", offset: " << VFId.Offset;
2976 // Print all type id that correspond to this GUID.
2978 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2980 Out << "vFuncId: (";
2981 auto Slot = Machine.getTypeIdSlot(It->second.first);
2984 Out << ", offset: " << VFId.Offset;
2989 void AssemblyWriter::printNonConstVCalls(
2990 const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
2991 Out << Tag << ": (";
2993 for (auto &VFuncId : VCallList) {
2995 printVFuncId(VFuncId);
3000 void AssemblyWriter::printConstVCalls(
3001 const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3002 Out << Tag << ": (";
3004 for (auto &ConstVCall : VCallList) {
3007 printVFuncId(ConstVCall.VFunc);
3008 if (!ConstVCall.Args.empty()) {
3010 printArgs(ConstVCall.Args);
3017 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3018 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3019 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3020 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3021 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3023 Out << "linkage: " << getLinkageName(LT);
3024 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3025 Out << ", live: " << GVFlags.Live;
3026 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3029 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3030 printAliasSummary(cast<AliasSummary>(&Summary));
3031 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3032 printFunctionSummary(cast<FunctionSummary>(&Summary));
3034 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3036 auto RefList = Summary.refs();
3037 if (!RefList.empty()) {
3040 for (auto &Ref : RefList) {
3042 if (Ref.isReadOnly())
3044 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3052 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3053 Out << "^" << Slot << " = gv: (";
3054 if (!VI.name().empty())
3055 Out << "name: \"" << VI.name() << "\"";
3057 Out << "guid: " << VI.getGUID();
3058 if (!VI.getSummaryList().empty()) {
3059 Out << ", summaries: (";
3061 for (auto &Summary : VI.getSummaryList()) {
3063 printSummary(*Summary);
3068 if (!VI.name().empty())
3069 Out << " ; guid = " << VI.getGUID();
3073 static void printMetadataIdentifier(StringRef Name,
3074 formatted_raw_ostream &Out) {
3076 Out << "<empty name> ";
3078 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3079 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3082 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3083 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3084 unsigned char C = Name[i];
3085 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3086 C == '.' || C == '_')
3089 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3094 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3096 printMetadataIdentifier(NMD->getName(), Out);
3098 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3102 // Write DIExpressions inline.
3103 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3104 MDNode *Op = NMD->getOperand(i);
3105 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3106 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3110 int Slot = Machine.getMetadataSlot(Op);
3119 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3120 formatted_raw_ostream &Out) {
3122 case GlobalValue::DefaultVisibility: break;
3123 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3124 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3128 static void PrintDSOLocation(const GlobalValue &GV,
3129 formatted_raw_ostream &Out) {
3130 // GVs with local linkage or non default visibility are implicitly dso_local,
3131 // so we don't print it.
3132 bool Implicit = GV.hasLocalLinkage() ||
3133 (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3134 if (GV.isDSOLocal() && !Implicit)
3135 Out << "dso_local ";
3138 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3139 formatted_raw_ostream &Out) {
3141 case GlobalValue::DefaultStorageClass: break;
3142 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3143 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3147 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3148 formatted_raw_ostream &Out) {
3150 case GlobalVariable::NotThreadLocal:
3152 case GlobalVariable::GeneralDynamicTLSModel:
3153 Out << "thread_local ";
3155 case GlobalVariable::LocalDynamicTLSModel:
3156 Out << "thread_local(localdynamic) ";
3158 case GlobalVariable::InitialExecTLSModel:
3159 Out << "thread_local(initialexec) ";
3161 case GlobalVariable::LocalExecTLSModel:
3162 Out << "thread_local(localexec) ";
3167 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3169 case GlobalVariable::UnnamedAddr::None:
3171 case GlobalVariable::UnnamedAddr::Local:
3172 return "local_unnamed_addr";
3173 case GlobalVariable::UnnamedAddr::Global:
3174 return "unnamed_addr";
3176 llvm_unreachable("Unknown UnnamedAddr");
3179 static void maybePrintComdat(formatted_raw_ostream &Out,
3180 const GlobalObject &GO) {
3181 const Comdat *C = GO.getComdat();
3185 if (isa<GlobalVariable>(GO))
3189 if (GO.getName() == C->getName())
3193 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3197 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3198 if (GV->isMaterializable())
3199 Out << "; Materializable\n";
3201 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3204 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3207 Out << getLinkageNameWithSpace(GV->getLinkage());
3208 PrintDSOLocation(*GV, Out);
3209 PrintVisibility(GV->getVisibility(), Out);
3210 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3211 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3212 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3216 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3217 Out << "addrspace(" << AddressSpace << ") ";
3218 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3219 Out << (GV->isConstant() ? "constant " : "global ");
3220 TypePrinter.print(GV->getValueType(), Out);
3222 if (GV->hasInitializer()) {
3224 writeOperand(GV->getInitializer(), false);
3227 if (GV->hasSection()) {
3228 Out << ", section \"";
3229 printEscapedString(GV->getSection(), Out);
3232 maybePrintComdat(Out, *GV);
3233 if (GV->getAlignment())
3234 Out << ", align " << GV->getAlignment();
3236 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3237 GV->getAllMetadata(MDs);
3238 printMetadataAttachments(MDs, ", ");
3240 auto Attrs = GV->getAttributes();
3241 if (Attrs.hasAttributes())
3242 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3244 printInfoComment(*GV);
3247 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3248 if (GIS->isMaterializable())
3249 Out << "; Materializable\n";
3251 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3254 Out << getLinkageNameWithSpace(GIS->getLinkage());
3255 PrintDSOLocation(*GIS, Out);
3256 PrintVisibility(GIS->getVisibility(), Out);
3257 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3258 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3259 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3263 if (isa<GlobalAlias>(GIS))
3265 else if (isa<GlobalIFunc>(GIS))
3268 llvm_unreachable("Not an alias or ifunc!");
3270 TypePrinter.print(GIS->getValueType(), Out);
3274 const Constant *IS = GIS->getIndirectSymbol();
3277 TypePrinter.print(GIS->getType(), Out);
3278 Out << " <<NULL ALIASEE>>";
3280 writeOperand(IS, !isa<ConstantExpr>(IS));
3283 printInfoComment(*GIS);
3287 void AssemblyWriter::printComdat(const Comdat *C) {
3291 void AssemblyWriter::printTypeIdentities() {
3292 if (TypePrinter.empty())
3297 // Emit all numbered types.
3298 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3299 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3300 Out << '%' << I << " = type ";
3302 // Make sure we print out at least one level of the type structure, so
3303 // that we do not get %2 = type %2
3304 TypePrinter.printStructBody(NumberedTypes[I], Out);
3308 auto &NamedTypes = TypePrinter.getNamedTypes();
3309 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3310 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3313 // Make sure we print out at least one level of the type structure, so
3314 // that we do not get %FILE = type %FILE
3315 TypePrinter.printStructBody(NamedTypes[I], Out);
3320 /// printFunction - Print all aspects of a function.
3321 void AssemblyWriter::printFunction(const Function *F) {
3322 // Print out the return type and name.
3325 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3327 if (F->isMaterializable())
3328 Out << "; Materializable\n";
3330 const AttributeList &Attrs = F->getAttributes();
3331 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3332 AttributeSet AS = Attrs.getFnAttributes();
3333 std::string AttrStr;
3335 for (const Attribute &Attr : AS) {
3336 if (!Attr.isStringAttribute()) {
3337 if (!AttrStr.empty()) AttrStr += ' ';
3338 AttrStr += Attr.getAsString();
3342 if (!AttrStr.empty())
3343 Out << "; Function Attrs: " << AttrStr << '\n';
3346 Machine.incorporateFunction(F);
3348 if (F->isDeclaration()) {
3350 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3351 F->getAllMetadata(MDs);
3352 printMetadataAttachments(MDs, " ");
3357 Out << getLinkageNameWithSpace(F->getLinkage());
3358 PrintDSOLocation(*F, Out);
3359 PrintVisibility(F->getVisibility(), Out);
3360 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3362 // Print the calling convention.
3363 if (F->getCallingConv() != CallingConv::C) {
3364 PrintCallingConv(F->getCallingConv(), Out);
3368 FunctionType *FT = F->getFunctionType();
3369 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3370 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3371 TypePrinter.print(F->getReturnType(), Out);
3373 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3376 // Loop over the arguments, printing them...
3377 if (F->isDeclaration() && !IsForDebug) {
3378 // We're only interested in the type here - don't print argument names.
3379 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3380 // Insert commas as we go... the first arg doesn't get a comma
3384 TypePrinter.print(FT->getParamType(I), Out);
3386 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3387 if (ArgAttrs.hasAttributes())
3388 Out << ' ' << ArgAttrs.getAsString();
3391 // The arguments are meaningful here, print them in detail.
3392 for (const Argument &Arg : F->args()) {
3393 // Insert commas as we go... the first arg doesn't get a comma
3394 if (Arg.getArgNo() != 0)
3396 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3400 // Finish printing arguments...
3401 if (FT->isVarArg()) {
3402 if (FT->getNumParams()) Out << ", ";
3403 Out << "..."; // Output varargs portion of signature!
3406 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3409 // We print the function address space if it is non-zero or if we are writing
3410 // a module with a non-zero program address space or if there is no valid
3411 // Module* so that the file can be parsed without the datalayout string.
3412 const Module *Mod = F->getParent();
3413 if (F->getAddressSpace() != 0 || !Mod ||
3414 Mod->getDataLayout().getProgramAddressSpace() != 0)
3415 Out << " addrspace(" << F->getAddressSpace() << ")";
3416 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3417 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3418 if (F->hasSection()) {
3419 Out << " section \"";
3420 printEscapedString(F->getSection(), Out);
3423 maybePrintComdat(Out, *F);
3424 if (F->getAlignment())
3425 Out << " align " << F->getAlignment();
3427 Out << " gc \"" << F->getGC() << '"';
3428 if (F->hasPrefixData()) {
3430 writeOperand(F->getPrefixData(), true);
3432 if (F->hasPrologueData()) {
3433 Out << " prologue ";
3434 writeOperand(F->getPrologueData(), true);
3436 if (F->hasPersonalityFn()) {
3437 Out << " personality ";
3438 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3441 if (F->isDeclaration()) {
3444 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3445 F->getAllMetadata(MDs);
3446 printMetadataAttachments(MDs, " ");
3449 // Output all of the function's basic blocks.
3450 for (const BasicBlock &BB : *F)
3451 printBasicBlock(&BB);
3453 // Output the function's use-lists.
3459 Machine.purgeFunction();
3462 /// printArgument - This member is called for every argument that is passed into
3463 /// the function. Simply print it out
3464 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3466 TypePrinter.print(Arg->getType(), Out);
3468 // Output parameter attributes list
3469 if (Attrs.hasAttributes())
3470 Out << ' ' << Attrs.getAsString();
3472 // Output name, if available...
3473 if (Arg->hasName()) {
3475 PrintLLVMName(Out, Arg);
3479 /// printBasicBlock - This member is called for each basic block in a method.
3480 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3481 if (BB->hasName()) { // Print out the label if it exists...
3483 PrintLLVMName(Out, BB->getName(), LabelPrefix);
3485 } else if (!BB->use_empty()) { // Don't print block # of no uses...
3486 Out << "\n; <label>:";
3487 int Slot = Machine.getLocalSlot(BB);
3494 if (!BB->getParent()) {
3495 Out.PadToColumn(50);
3496 Out << "; Error: Block without parent!";
3497 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
3498 // Output predecessors for the block.
3499 Out.PadToColumn(50);
3501 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3504 Out << " No predecessors!";
3507 writeOperand(*PI, false);
3508 for (++PI; PI != PE; ++PI) {
3510 writeOperand(*PI, false);
3517 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3519 // Output all of the instructions in the basic block...
3520 for (const Instruction &I : *BB) {
3521 printInstructionLine(I);
3524 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3527 /// printInstructionLine - Print an instruction and a newline character.
3528 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3529 printInstruction(I);
3533 /// printGCRelocateComment - print comment after call to the gc.relocate
3534 /// intrinsic indicating base and derived pointer names.
3535 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3537 writeOperand(Relocate.getBasePtr(), false);
3539 writeOperand(Relocate.getDerivedPtr(), false);
3543 /// printInfoComment - Print a little comment after the instruction indicating
3544 /// which slot it occupies.
3545 void AssemblyWriter::printInfoComment(const Value &V) {
3546 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3547 printGCRelocateComment(*Relocate);
3549 if (AnnotationWriter)
3550 AnnotationWriter->printInfoComment(V, Out);
3553 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3555 // We print the address space of the call if it is non-zero.
3556 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3557 bool PrintAddrSpace = CallAddrSpace != 0;
3558 if (!PrintAddrSpace) {
3559 const Module *Mod = getModuleFromVal(I);
3560 // We also print it if it is zero but not equal to the program address space
3561 // or if we can't find a valid Module* to make it possible to parse
3562 // the resulting file even without a datalayout string.
3563 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3564 PrintAddrSpace = true;
3567 Out << " addrspace(" << CallAddrSpace << ")";
3570 // This member is called for each Instruction in a function..
3571 void AssemblyWriter::printInstruction(const Instruction &I) {
3572 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3574 // Print out indentation for an instruction.
3577 // Print out name if it exists...
3579 PrintLLVMName(Out, &I);
3581 } else if (!I.getType()->isVoidTy()) {
3582 // Print out the def slot taken.
3583 int SlotNum = Machine.getLocalSlot(&I);
3585 Out << "<badref> = ";
3587 Out << '%' << SlotNum << " = ";
3590 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3591 if (CI->isMustTailCall())
3593 else if (CI->isTailCall())
3595 else if (CI->isNoTailCall())
3599 // Print out the opcode...
3600 Out << I.getOpcodeName();
3602 // If this is an atomic load or store, print out the atomic marker.
3603 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
3604 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3607 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3610 // If this is a volatile operation, print out the volatile marker.
3611 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
3612 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3613 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3614 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3617 // Print out optimization information.
3618 WriteOptimizationInfo(Out, &I);
3620 // Print out the compare instruction predicates
3621 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3622 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3624 // Print out the atomicrmw operation
3625 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3626 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3628 // Print out the type of the operands...
3629 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3631 // Special case conditional branches to swizzle the condition out to the front
3632 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3633 const BranchInst &BI(cast<BranchInst>(I));
3635 writeOperand(BI.getCondition(), true);
3637 writeOperand(BI.getSuccessor(0), true);
3639 writeOperand(BI.getSuccessor(1), true);
3641 } else if (isa<SwitchInst>(I)) {
3642 const SwitchInst& SI(cast<SwitchInst>(I));
3643 // Special case switch instruction to get formatting nice and correct.
3645 writeOperand(SI.getCondition(), true);
3647 writeOperand(SI.getDefaultDest(), true);
3649 for (auto Case : SI.cases()) {
3651 writeOperand(Case.getCaseValue(), true);
3653 writeOperand(Case.getCaseSuccessor(), true);
3656 } else if (isa<IndirectBrInst>(I)) {
3657 // Special case indirectbr instruction to get formatting nice and correct.
3659 writeOperand(Operand, true);
3662 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3665 writeOperand(I.getOperand(i), true);
3668 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3670 TypePrinter.print(I.getType(), Out);
3673 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3674 if (op) Out << ", ";
3676 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3677 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3679 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3681 writeOperand(I.getOperand(0), true);
3682 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3684 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3686 writeOperand(I.getOperand(0), true); Out << ", ";
3687 writeOperand(I.getOperand(1), true);
3688 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3690 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3692 TypePrinter.print(I.getType(), Out);
3693 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3696 if (LPI->isCleanup())
3699 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3700 if (i != 0 || LPI->isCleanup()) Out << "\n";
3701 if (LPI->isCatch(i))
3706 writeOperand(LPI->getClause(i), true);
3708 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3710 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3713 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3716 writeOperand(PadBB, /*PrintType=*/true);
3720 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3721 writeOperand(UnwindDest, /*PrintType=*/true);
3724 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3726 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3728 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3732 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3735 } else if (isa<ReturnInst>(I) && !Operand) {
3737 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3739 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3742 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3743 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3745 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3748 if (CRI->hasUnwindDest())
3749 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3752 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3753 // Print the calling convention being used.
3754 if (CI->getCallingConv() != CallingConv::C) {
3756 PrintCallingConv(CI->getCallingConv(), Out);
3759 Operand = CI->getCalledValue();
3760 FunctionType *FTy = CI->getFunctionType();
3761 Type *RetTy = FTy->getReturnType();
3762 const AttributeList &PAL = CI->getAttributes();
3764 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3765 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3767 // Only print addrspace(N) if necessary:
3768 maybePrintCallAddrSpace(Operand, &I, Out);
3770 // If possible, print out the short form of the call instruction. We can
3771 // only do this if the first argument is a pointer to a nonvararg function,
3772 // and if the return type is not a pointer to a function.
3775 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3777 writeOperand(Operand, false);
3779 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3782 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3785 // Emit an ellipsis if this is a musttail call in a vararg function. This
3786 // is only to aid readability, musttail calls forward varargs by default.
3787 if (CI->isMustTailCall() && CI->getParent() &&
3788 CI->getParent()->getParent() &&
3789 CI->getParent()->getParent()->isVarArg())
3793 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3794 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3796 writeOperandBundles(CI);
3797 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3798 Operand = II->getCalledValue();
3799 FunctionType *FTy = II->getFunctionType();
3800 Type *RetTy = FTy->getReturnType();
3801 const AttributeList &PAL = II->getAttributes();
3803 // Print the calling convention being used.
3804 if (II->getCallingConv() != CallingConv::C) {
3806 PrintCallingConv(II->getCallingConv(), Out);
3809 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3810 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3812 // Only print addrspace(N) if necessary:
3813 maybePrintCallAddrSpace(Operand, &I, Out);
3815 // If possible, print out the short form of the invoke instruction. We can
3816 // only do this if the first argument is a pointer to a nonvararg function,
3817 // and if the return type is not a pointer to a function.
3820 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3822 writeOperand(Operand, false);
3824 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3827 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3831 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3832 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3834 writeOperandBundles(II);
3837 writeOperand(II->getNormalDest(), true);
3839 writeOperand(II->getUnwindDest(), true);
3840 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3842 if (AI->isUsedWithInAlloca())
3844 if (AI->isSwiftError())
3845 Out << "swifterror ";
3846 TypePrinter.print(AI->getAllocatedType(), Out);
3848 // Explicitly write the array size if the code is broken, if it's an array
3849 // allocation, or if the type is not canonical for scalar allocations. The
3850 // latter case prevents the type from mutating when round-tripping through
3852 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3853 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3855 writeOperand(AI->getArraySize(), true);
3857 if (AI->getAlignment()) {
3858 Out << ", align " << AI->getAlignment();
3861 unsigned AddrSpace = AI->getType()->getAddressSpace();
3862 if (AddrSpace != 0) {
3863 Out << ", addrspace(" << AddrSpace << ')';
3865 } else if (isa<CastInst>(I)) {
3868 writeOperand(Operand, true); // Work with broken code
3871 TypePrinter.print(I.getType(), Out);
3872 } else if (isa<VAArgInst>(I)) {
3875 writeOperand(Operand, true); // Work with broken code
3878 TypePrinter.print(I.getType(), Out);
3879 } else if (Operand) { // Print the normal way.
3880 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3882 TypePrinter.print(GEP->getSourceElementType(), Out);
3884 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3886 TypePrinter.print(LI->getType(), Out);
3890 // PrintAllTypes - Instructions who have operands of all the same type
3891 // omit the type from all but the first operand. If the instruction has
3892 // different type operands (for example br), then they are all printed.
3893 bool PrintAllTypes = false;
3894 Type *TheType = Operand->getType();
3896 // Select, Store and ShuffleVector always print all types.
3897 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3898 || isa<ReturnInst>(I)) {
3899 PrintAllTypes = true;
3901 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3902 Operand = I.getOperand(i);
3903 // note that Operand shouldn't be null, but the test helps make dump()
3904 // more tolerant of malformed IR
3905 if (Operand && Operand->getType() != TheType) {
3906 PrintAllTypes = true; // We have differing types! Print them all!
3912 if (!PrintAllTypes) {
3914 TypePrinter.print(TheType, Out);
3918 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3920 writeOperand(I.getOperand(i), PrintAllTypes);
3924 // Print atomic ordering/alignment for memory operations
3925 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3927 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
3928 if (LI->getAlignment())
3929 Out << ", align " << LI->getAlignment();
3930 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3932 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
3933 if (SI->getAlignment())
3934 Out << ", align " << SI->getAlignment();
3935 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3936 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3937 CXI->getFailureOrdering(), CXI->getSyncScopeID());
3938 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3939 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3940 RMWI->getSyncScopeID());
3941 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3942 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
3945 // Print Metadata info.
3946 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3947 I.getAllMetadata(InstMD);
3948 printMetadataAttachments(InstMD, ", ");
3950 // Print a nice comment.
3951 printInfoComment(I);
3954 void AssemblyWriter::printMetadataAttachments(
3955 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3956 StringRef Separator) {
3960 if (MDNames.empty())
3961 MDs[0].second->getContext().getMDKindNames(MDNames);
3963 for (const auto &I : MDs) {
3964 unsigned Kind = I.first;
3966 if (Kind < MDNames.size()) {
3968 printMetadataIdentifier(MDNames[Kind], Out);
3970 Out << "!<unknown kind #" << Kind << ">";
3972 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3976 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3977 Out << '!' << Slot << " = ";
3978 printMDNodeBody(Node);
3982 void AssemblyWriter::writeAllMDNodes() {
3983 SmallVector<const MDNode *, 16> Nodes;
3984 Nodes.resize(Machine.mdn_size());
3985 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3987 Nodes[I->second] = cast<MDNode>(I->first);
3989 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3990 writeMDNode(i, Nodes[i]);
3994 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3995 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3998 void AssemblyWriter::writeAllAttributeGroups() {
3999 std::vector<std::pair<AttributeSet, unsigned>> asVec;
4000 asVec.resize(Machine.as_size());
4002 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4004 asVec[I->second] = *I;
4006 for (const auto &I : asVec)
4007 Out << "attributes #" << I.second << " = { "
4008 << I.first.getAsString(true) << " }\n";
4011 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4012 bool IsInFunction = Machine.getFunction();
4016 Out << "uselistorder";
4017 if (const BasicBlock *BB =
4018 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4020 writeOperand(BB->getParent(), false);
4022 writeOperand(BB, false);
4025 writeOperand(Order.V, true);
4029 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4030 Out << Order.Shuffle[0];
4031 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4032 Out << ", " << Order.Shuffle[I];
4036 void AssemblyWriter::printUseLists(const Function *F) {
4038 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4043 Out << "\n; uselistorder directives\n";
4045 printUseListOrder(UseListOrders.back());
4046 UseListOrders.pop_back();
4050 //===----------------------------------------------------------------------===//
4051 // External Interface declarations
4052 //===----------------------------------------------------------------------===//
4054 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4055 bool ShouldPreserveUseListOrder,
4056 bool IsForDebug) const {
4057 SlotTracker SlotTable(this->getParent());
4058 formatted_raw_ostream OS(ROS);
4059 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4061 ShouldPreserveUseListOrder);
4062 W.printFunction(this);
4065 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4066 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4067 SlotTracker SlotTable(this);
4068 formatted_raw_ostream OS(ROS);
4069 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4070 ShouldPreserveUseListOrder);
4071 W.printModule(this);
4074 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4075 SlotTracker SlotTable(getParent());
4076 formatted_raw_ostream OS(ROS);
4077 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4078 W.printNamedMDNode(this);
4081 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4082 bool IsForDebug) const {
4083 Optional<SlotTracker> LocalST;
4084 SlotTracker *SlotTable;
4085 if (auto *ST = MST.getMachine())
4088 LocalST.emplace(getParent());
4089 SlotTable = &*LocalST;
4092 formatted_raw_ostream OS(ROS);
4093 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4094 W.printNamedMDNode(this);
4097 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4098 PrintLLVMName(ROS, getName(), ComdatPrefix);
4099 ROS << " = comdat ";
4101 switch (getSelectionKind()) {
4105 case Comdat::ExactMatch:
4106 ROS << "exactmatch";
4108 case Comdat::Largest:
4111 case Comdat::NoDuplicates:
4112 ROS << "noduplicates";
4114 case Comdat::SameSize:
4122 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4124 TP.print(const_cast<Type*>(this), OS);
4129 // If the type is a named struct type, print the body as well.
4130 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4131 if (!STy->isLiteral()) {
4133 TP.printStructBody(STy, OS);
4137 static bool isReferencingMDNode(const Instruction &I) {
4138 if (const auto *CI = dyn_cast<CallInst>(&I))
4139 if (Function *F = CI->getCalledFunction())
4140 if (F->isIntrinsic())
4141 for (auto &Op : I.operands())
4142 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4143 if (isa<MDNode>(V->getMetadata()))
4148 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4149 bool ShouldInitializeAllMetadata = false;
4150 if (auto *I = dyn_cast<Instruction>(this))
4151 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4152 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4153 ShouldInitializeAllMetadata = true;
4155 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4156 print(ROS, MST, IsForDebug);
4159 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4160 bool IsForDebug) const {
4161 formatted_raw_ostream OS(ROS);
4162 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4163 SlotTracker &SlotTable =
4164 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4165 auto incorporateFunction = [&](const Function *F) {
4167 MST.incorporateFunction(*F);
4170 if (const Instruction *I = dyn_cast<Instruction>(this)) {
4171 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4172 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4173 W.printInstruction(*I);
4174 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4175 incorporateFunction(BB->getParent());
4176 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4177 W.printBasicBlock(BB);
4178 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4179 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4180 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4182 else if (const Function *F = dyn_cast<Function>(GV))
4185 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4186 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4187 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4188 } else if (const Constant *C = dyn_cast<Constant>(this)) {
4189 TypePrinting TypePrinter;
4190 TypePrinter.print(C->getType(), OS);
4192 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4193 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4194 this->printAsOperand(OS, /* PrintType */ true, MST);
4196 llvm_unreachable("Unknown value to print out!");
4200 /// Print without a type, skipping the TypePrinting object.
4202 /// \return \c true iff printing was successful.
4203 static bool printWithoutType(const Value &V, raw_ostream &O,
4204 SlotTracker *Machine, const Module *M) {
4205 if (V.hasName() || isa<GlobalValue>(V) ||
4206 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4207 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4213 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4214 ModuleSlotTracker &MST) {
4215 TypePrinting TypePrinter(MST.getModule());
4217 TypePrinter.print(V.getType(), O);
4221 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4225 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4226 const Module *M) const {
4228 M = getModuleFromVal(this);
4231 if (printWithoutType(*this, O, nullptr, M))
4234 SlotTracker Machine(
4235 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4236 ModuleSlotTracker MST(Machine, M);
4237 printAsOperandImpl(*this, O, PrintType, MST);
4240 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4241 ModuleSlotTracker &MST) const {
4243 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4246 printAsOperandImpl(*this, O, PrintType, MST);
4249 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4250 ModuleSlotTracker &MST, const Module *M,
4251 bool OnlyAsOperand) {
4252 formatted_raw_ostream OS(ROS);
4254 TypePrinting TypePrinter(M);
4256 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4257 /* FromValue */ true);
4259 auto *N = dyn_cast<MDNode>(&MD);
4260 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4264 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4267 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4268 ModuleSlotTracker MST(M, isa<MDNode>(this));
4269 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4272 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4273 const Module *M) const {
4274 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4277 void Metadata::print(raw_ostream &OS, const Module *M,
4278 bool /*IsForDebug*/) const {
4279 ModuleSlotTracker MST(M, isa<MDNode>(this));
4280 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4283 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4284 const Module *M, bool /*IsForDebug*/) const {
4285 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4288 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4289 SlotTracker SlotTable(this);
4290 formatted_raw_ostream OS(ROS);
4291 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4292 W.printModuleSummaryIndex();
4295 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4296 // Value::dump - allow easy printing of Values from the debugger.
4298 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4300 // Type::dump - allow easy printing of Types from the debugger.
4302 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4304 // Module::dump() - Allow printing of Modules from the debugger.
4306 void Module::dump() const {
4307 print(dbgs(), nullptr,
4308 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4311 // Allow printing of Comdats from the debugger.
4313 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4315 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4317 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4320 void Metadata::dump() const { dump(nullptr); }
4323 void Metadata::dump(const Module *M) const {
4324 print(dbgs(), M, /*IsForDebug=*/true);
4328 // Allow printing of ModuleSummaryIndex from the debugger.
4330 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }