1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This library implements `print` family of functions in classes like
10 // Module, Function, Value, etc. In-memory representation of those classes is
11 // converted to IR strings.
13 // Note that these routines must be extremely tolerant of various errors in the
14 // LLVM code, because it can be used for debugging transformations.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/Argument.h"
34 #include "llvm/IR/AssemblyAnnotationWriter.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Comdat.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfoMetadata.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalIFunc.h"
47 #include "llvm/IR/GlobalIndirectSymbol.h"
48 #include "llvm/IR/GlobalObject.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/IRPrintingPasses.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.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/Type.h"
64 #include "llvm/IR/TypeFinder.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/User.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/Support/AtomicOrdering.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/Format.h"
74 #include "llvm/Support/FormattedStream.h"
75 #include "llvm/Support/raw_ostream.h"
90 // Make virtual table appear in this compilation unit.
91 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
97 using OrderMap
= MapVector
<const Value
*, unsigned>;
99 using UseListOrderMap
=
100 DenseMap
<const Function
*, MapVector
<const Value
*, std::vector
<unsigned>>>;
102 /// Look for a value that might be wrapped as metadata, e.g. a value in a
103 /// metadata operand. Returns the input value as-is if it is not wrapped.
104 static const Value
*skipMetadataWrapper(const Value
*V
) {
105 if (const auto *MAV
= dyn_cast
<MetadataAsValue
>(V
))
106 if (const auto *VAM
= dyn_cast
<ValueAsMetadata
>(MAV
->getMetadata()))
107 return VAM
->getValue();
111 static void orderValue(const Value
*V
, OrderMap
&OM
) {
115 if (const Constant
*C
= dyn_cast
<Constant
>(V
))
116 if (C
->getNumOperands() && !isa
<GlobalValue
>(C
))
117 for (const Value
*Op
: C
->operands())
118 if (!isa
<BasicBlock
>(Op
) && !isa
<GlobalValue
>(Op
))
121 // Note: we cannot cache this lookup above, since inserting into the map
122 // changes the map's size, and thus affects the other IDs.
123 unsigned ID
= OM
.size() + 1;
127 static OrderMap
orderModule(const Module
*M
) {
130 for (const GlobalVariable
&G
: M
->globals()) {
131 if (G
.hasInitializer())
132 if (!isa
<GlobalValue
>(G
.getInitializer()))
133 orderValue(G
.getInitializer(), OM
);
136 for (const GlobalAlias
&A
: M
->aliases()) {
137 if (!isa
<GlobalValue
>(A
.getAliasee()))
138 orderValue(A
.getAliasee(), OM
);
141 for (const GlobalIFunc
&I
: M
->ifuncs()) {
142 if (!isa
<GlobalValue
>(I
.getResolver()))
143 orderValue(I
.getResolver(), OM
);
146 for (const Function
&F
: *M
) {
147 for (const Use
&U
: F
.operands())
148 if (!isa
<GlobalValue
>(U
.get()))
149 orderValue(U
.get(), OM
);
153 if (F
.isDeclaration())
156 for (const Argument
&A
: F
.args())
158 for (const BasicBlock
&BB
: F
) {
160 for (const Instruction
&I
: BB
) {
161 for (const Value
*Op
: I
.operands()) {
162 Op
= skipMetadataWrapper(Op
);
163 if ((isa
<Constant
>(*Op
) && !isa
<GlobalValue
>(*Op
)) ||
174 static std::vector
<unsigned>
175 predictValueUseListOrder(const Value
*V
, unsigned ID
, const OrderMap
&OM
) {
176 // Predict use-list order for this one.
177 using Entry
= std::pair
<const Use
*, unsigned>;
178 SmallVector
<Entry
, 64> List
;
179 for (const Use
&U
: V
->uses())
180 // Check if this user will be serialized.
181 if (OM
.lookup(U
.getUser()))
182 List
.push_back(std::make_pair(&U
, List
.size()));
185 // We may have lost some users.
188 // When referencing a value before its declaration, a temporary value is
189 // created, which will later be RAUWed with the actual value. This reverses
190 // the use list. This happens for all values apart from basic blocks.
191 bool GetsReversed
= !isa
<BasicBlock
>(V
);
192 if (auto *BA
= dyn_cast
<BlockAddress
>(V
))
193 ID
= OM
.lookup(BA
->getBasicBlock());
194 llvm::sort(List
, [&](const Entry
&L
, const Entry
&R
) {
195 const Use
*LU
= L
.first
;
196 const Use
*RU
= R
.first
;
200 auto LID
= OM
.lookup(LU
->getUser());
201 auto RID
= OM
.lookup(RU
->getUser());
203 // If ID is 4, then expect: 7 6 5 1 2 3.
217 // LID and RID are equal, so we have different operands of the same user.
218 // Assume operands are added in order for all instructions.
221 return LU
->getOperandNo() < RU
->getOperandNo();
222 return LU
->getOperandNo() > RU
->getOperandNo();
225 if (llvm::is_sorted(List
, [](const Entry
&L
, const Entry
&R
) {
226 return L
.second
< R
.second
;
228 // Order is already correct.
231 // Store the shuffle.
232 std::vector
<unsigned> Shuffle(List
.size());
233 for (size_t I
= 0, E
= List
.size(); I
!= E
; ++I
)
234 Shuffle
[I
] = List
[I
].second
;
238 static UseListOrderMap
predictUseListOrder(const Module
*M
) {
239 OrderMap OM
= orderModule(M
);
240 UseListOrderMap ULOM
;
241 for (const auto &Pair
: OM
) {
242 const Value
*V
= Pair
.first
;
243 if (V
->use_empty() || std::next(V
->use_begin()) == V
->use_end())
246 std::vector
<unsigned> Shuffle
=
247 predictValueUseListOrder(V
, Pair
.second
, OM
);
251 const Function
*F
= nullptr;
252 if (auto *I
= dyn_cast
<Instruction
>(V
))
253 F
= I
->getFunction();
254 if (auto *A
= dyn_cast
<Argument
>(V
))
256 if (auto *BB
= dyn_cast
<BasicBlock
>(V
))
258 ULOM
[F
][V
] = std::move(Shuffle
);
263 static const Module
*getModuleFromVal(const Value
*V
) {
264 if (const Argument
*MA
= dyn_cast
<Argument
>(V
))
265 return MA
->getParent() ? MA
->getParent()->getParent() : nullptr;
267 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
268 return BB
->getParent() ? BB
->getParent()->getParent() : nullptr;
270 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
271 const Function
*M
= I
->getParent() ? I
->getParent()->getParent() : nullptr;
272 return M
? M
->getParent() : nullptr;
275 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
))
276 return GV
->getParent();
278 if (const auto *MAV
= dyn_cast
<MetadataAsValue
>(V
)) {
279 for (const User
*U
: MAV
->users())
280 if (isa
<Instruction
>(U
))
281 if (const Module
*M
= getModuleFromVal(U
))
289 static void PrintCallingConv(unsigned cc
, raw_ostream
&Out
) {
291 default: Out
<< "cc" << cc
; break;
292 case CallingConv::Fast
: Out
<< "fastcc"; break;
293 case CallingConv::Cold
: Out
<< "coldcc"; break;
294 case CallingConv::WebKit_JS
: Out
<< "webkit_jscc"; break;
295 case CallingConv::AnyReg
: Out
<< "anyregcc"; break;
296 case CallingConv::PreserveMost
: Out
<< "preserve_mostcc"; break;
297 case CallingConv::PreserveAll
: Out
<< "preserve_allcc"; break;
298 case CallingConv::CXX_FAST_TLS
: Out
<< "cxx_fast_tlscc"; break;
299 case CallingConv::GHC
: Out
<< "ghccc"; break;
300 case CallingConv::Tail
: Out
<< "tailcc"; break;
301 case CallingConv::CFGuard_Check
: Out
<< "cfguard_checkcc"; break;
302 case CallingConv::X86_StdCall
: Out
<< "x86_stdcallcc"; break;
303 case CallingConv::X86_FastCall
: Out
<< "x86_fastcallcc"; break;
304 case CallingConv::X86_ThisCall
: Out
<< "x86_thiscallcc"; break;
305 case CallingConv::X86_RegCall
: Out
<< "x86_regcallcc"; break;
306 case CallingConv::X86_VectorCall
:Out
<< "x86_vectorcallcc"; break;
307 case CallingConv::Intel_OCL_BI
: Out
<< "intel_ocl_bicc"; break;
308 case CallingConv::ARM_APCS
: Out
<< "arm_apcscc"; break;
309 case CallingConv::ARM_AAPCS
: Out
<< "arm_aapcscc"; break;
310 case CallingConv::ARM_AAPCS_VFP
: Out
<< "arm_aapcs_vfpcc"; break;
311 case CallingConv::AArch64_VectorCall
: Out
<< "aarch64_vector_pcs"; break;
312 case CallingConv::AArch64_SVE_VectorCall
:
313 Out
<< "aarch64_sve_vector_pcs";
315 case CallingConv::MSP430_INTR
: Out
<< "msp430_intrcc"; break;
316 case CallingConv::AVR_INTR
: Out
<< "avr_intrcc "; break;
317 case CallingConv::AVR_SIGNAL
: Out
<< "avr_signalcc "; break;
318 case CallingConv::PTX_Kernel
: Out
<< "ptx_kernel"; break;
319 case CallingConv::PTX_Device
: Out
<< "ptx_device"; break;
320 case CallingConv::X86_64_SysV
: Out
<< "x86_64_sysvcc"; break;
321 case CallingConv::Win64
: Out
<< "win64cc"; break;
322 case CallingConv::SPIR_FUNC
: Out
<< "spir_func"; break;
323 case CallingConv::SPIR_KERNEL
: Out
<< "spir_kernel"; break;
324 case CallingConv::Swift
: Out
<< "swiftcc"; break;
325 case CallingConv::SwiftTail
: Out
<< "swifttailcc"; break;
326 case CallingConv::X86_INTR
: Out
<< "x86_intrcc"; break;
327 case CallingConv::HHVM
: Out
<< "hhvmcc"; break;
328 case CallingConv::HHVM_C
: Out
<< "hhvm_ccc"; break;
329 case CallingConv::AMDGPU_VS
: Out
<< "amdgpu_vs"; break;
330 case CallingConv::AMDGPU_LS
: Out
<< "amdgpu_ls"; break;
331 case CallingConv::AMDGPU_HS
: Out
<< "amdgpu_hs"; break;
332 case CallingConv::AMDGPU_ES
: Out
<< "amdgpu_es"; break;
333 case CallingConv::AMDGPU_GS
: Out
<< "amdgpu_gs"; break;
334 case CallingConv::AMDGPU_PS
: Out
<< "amdgpu_ps"; break;
335 case CallingConv::AMDGPU_CS
: Out
<< "amdgpu_cs"; break;
336 case CallingConv::AMDGPU_KERNEL
: Out
<< "amdgpu_kernel"; break;
337 case CallingConv::AMDGPU_Gfx
: Out
<< "amdgpu_gfx"; break;
349 void llvm::printLLVMNameWithoutPrefix(raw_ostream
&OS
, StringRef Name
) {
350 assert(!Name
.empty() && "Cannot get empty name!");
352 // Scan the name to see if it needs quotes first.
353 bool NeedsQuotes
= isdigit(static_cast<unsigned char>(Name
[0]));
355 for (unsigned i
= 0, e
= Name
.size(); i
!= e
; ++i
) {
356 // By making this unsigned, the value passed in to isalnum will always be
357 // in the range 0-255. This is important when building with MSVC because
358 // its implementation will assert. This situation can arise when dealing
359 // with UTF-8 multibyte characters.
360 unsigned char C
= Name
[i
];
361 if (!isalnum(static_cast<unsigned char>(C
)) && C
!= '-' && C
!= '.' &&
369 // If we didn't need any quotes, just write out the name in one blast.
375 // Okay, we need quotes. Output the quotes and escape any scary characters as
378 printEscapedString(Name
, OS
);
382 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
383 /// (if the string only contains simple characters) or is surrounded with ""'s
384 /// (if it has special chars in it). Print it out.
385 static void PrintLLVMName(raw_ostream
&OS
, StringRef Name
, PrefixType Prefix
) {
401 printLLVMNameWithoutPrefix(OS
, Name
);
404 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
405 /// (if the string only contains simple characters) or is surrounded with ""'s
406 /// (if it has special chars in it). Print it out.
407 static void PrintLLVMName(raw_ostream
&OS
, const Value
*V
) {
408 PrintLLVMName(OS
, V
->getName(),
409 isa
<GlobalValue
>(V
) ? GlobalPrefix
: LocalPrefix
);
412 static void PrintShuffleMask(raw_ostream
&Out
, Type
*Ty
, ArrayRef
<int> Mask
) {
414 if (isa
<ScalableVectorType
>(Ty
))
416 Out
<< Mask
.size() << " x i32> ";
417 bool FirstElt
= true;
418 if (all_of(Mask
, [](int Elt
) { return Elt
== 0; })) {
419 Out
<< "zeroinitializer";
420 } else if (all_of(Mask
, [](int Elt
) { return Elt
== UndefMaskElem
; })) {
424 for (int Elt
: Mask
) {
430 if (Elt
== UndefMaskElem
)
443 TypePrinting(const Module
*M
= nullptr) : DeferredM(M
) {}
445 TypePrinting(const TypePrinting
&) = delete;
446 TypePrinting
&operator=(const TypePrinting
&) = delete;
448 /// The named types that are used by the current module.
449 TypeFinder
&getNamedTypes();
451 /// The numbered types, number to type mapping.
452 std::vector
<StructType
*> &getNumberedTypes();
456 void print(Type
*Ty
, raw_ostream
&OS
);
458 void printStructBody(StructType
*Ty
, raw_ostream
&OS
);
461 void incorporateTypes();
463 /// A module to process lazily when needed. Set to nullptr as soon as used.
464 const Module
*DeferredM
;
466 TypeFinder NamedTypes
;
468 // The numbered types, along with their value.
469 DenseMap
<StructType
*, unsigned> Type2Number
;
471 std::vector
<StructType
*> NumberedTypes
;
474 } // end anonymous namespace
476 TypeFinder
&TypePrinting::getNamedTypes() {
481 std::vector
<StructType
*> &TypePrinting::getNumberedTypes() {
484 // We know all the numbers that each type is used and we know that it is a
485 // dense assignment. Convert the map to an index table, if it's not done
486 // already (judging from the sizes):
487 if (NumberedTypes
.size() == Type2Number
.size())
488 return NumberedTypes
;
490 NumberedTypes
.resize(Type2Number
.size());
491 for (const auto &P
: Type2Number
) {
492 assert(P
.second
< NumberedTypes
.size() && "Didn't get a dense numbering?");
493 assert(!NumberedTypes
[P
.second
] && "Didn't get a unique numbering?");
494 NumberedTypes
[P
.second
] = P
.first
;
496 return NumberedTypes
;
499 bool TypePrinting::empty() {
501 return NamedTypes
.empty() && Type2Number
.empty();
504 void TypePrinting::incorporateTypes() {
508 NamedTypes
.run(*DeferredM
, false);
511 // The list of struct types we got back includes all the struct types, split
512 // the unnamed ones out to a numbering and remove the anonymous structs.
513 unsigned NextNumber
= 0;
515 std::vector
<StructType
*>::iterator NextToUse
= NamedTypes
.begin(), I
, E
;
516 for (I
= NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
) {
517 StructType
*STy
= *I
;
519 // Ignore anonymous types.
520 if (STy
->isLiteral())
523 if (STy
->getName().empty())
524 Type2Number
[STy
] = NextNumber
++;
529 NamedTypes
.erase(NextToUse
, NamedTypes
.end());
532 /// Write the specified type to the specified raw_ostream, making use of type
533 /// names or up references to shorten the type name where possible.
534 void TypePrinting::print(Type
*Ty
, raw_ostream
&OS
) {
535 switch (Ty
->getTypeID()) {
536 case Type::VoidTyID
: OS
<< "void"; return;
537 case Type::HalfTyID
: OS
<< "half"; return;
538 case Type::BFloatTyID
: OS
<< "bfloat"; return;
539 case Type::FloatTyID
: OS
<< "float"; return;
540 case Type::DoubleTyID
: OS
<< "double"; return;
541 case Type::X86_FP80TyID
: OS
<< "x86_fp80"; return;
542 case Type::FP128TyID
: OS
<< "fp128"; return;
543 case Type::PPC_FP128TyID
: OS
<< "ppc_fp128"; return;
544 case Type::LabelTyID
: OS
<< "label"; return;
545 case Type::MetadataTyID
: OS
<< "metadata"; return;
546 case Type::X86_MMXTyID
: OS
<< "x86_mmx"; return;
547 case Type::X86_AMXTyID
: OS
<< "x86_amx"; return;
548 case Type::TokenTyID
: OS
<< "token"; return;
549 case Type::IntegerTyID
:
550 OS
<< 'i' << cast
<IntegerType
>(Ty
)->getBitWidth();
553 case Type::FunctionTyID
: {
554 FunctionType
*FTy
= cast
<FunctionType
>(Ty
);
555 print(FTy
->getReturnType(), OS
);
557 for (FunctionType::param_iterator I
= FTy
->param_begin(),
558 E
= FTy
->param_end(); I
!= E
; ++I
) {
559 if (I
!= FTy
->param_begin())
563 if (FTy
->isVarArg()) {
564 if (FTy
->getNumParams()) OS
<< ", ";
570 case Type::StructTyID
: {
571 StructType
*STy
= cast
<StructType
>(Ty
);
573 if (STy
->isLiteral())
574 return printStructBody(STy
, OS
);
576 if (!STy
->getName().empty())
577 return PrintLLVMName(OS
, STy
->getName(), LocalPrefix
);
580 const auto I
= Type2Number
.find(STy
);
581 if (I
!= Type2Number
.end())
582 OS
<< '%' << I
->second
;
583 else // Not enumerated, print the hex address.
584 OS
<< "%\"type " << STy
<< '\"';
587 case Type::PointerTyID
: {
588 PointerType
*PTy
= cast
<PointerType
>(Ty
);
589 if (PTy
->isOpaque()) {
591 if (unsigned AddressSpace
= PTy
->getAddressSpace())
592 OS
<< " addrspace(" << AddressSpace
<< ')';
595 print(PTy
->getElementType(), OS
);
596 if (unsigned AddressSpace
= PTy
->getAddressSpace())
597 OS
<< " addrspace(" << AddressSpace
<< ')';
601 case Type::ArrayTyID
: {
602 ArrayType
*ATy
= cast
<ArrayType
>(Ty
);
603 OS
<< '[' << ATy
->getNumElements() << " x ";
604 print(ATy
->getElementType(), OS
);
608 case Type::FixedVectorTyID
:
609 case Type::ScalableVectorTyID
: {
610 VectorType
*PTy
= cast
<VectorType
>(Ty
);
611 ElementCount EC
= PTy
->getElementCount();
615 OS
<< EC
.getKnownMinValue() << " x ";
616 print(PTy
->getElementType(), OS
);
621 llvm_unreachable("Invalid TypeID");
624 void TypePrinting::printStructBody(StructType
*STy
, raw_ostream
&OS
) {
625 if (STy
->isOpaque()) {
633 if (STy
->getNumElements() == 0) {
636 StructType::element_iterator I
= STy
->element_begin();
639 for (StructType::element_iterator E
= STy
->element_end(); I
!= E
; ++I
) {
650 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() {}
654 //===----------------------------------------------------------------------===//
655 // SlotTracker Class: Enumerate slot numbers for unnamed values
656 //===----------------------------------------------------------------------===//
657 /// This class provides computation of slot numbers for LLVM Assembly writing.
659 class SlotTracker
: public AbstractSlotTrackerStorage
{
661 /// ValueMap - A mapping of Values to slot numbers.
662 using ValueMap
= DenseMap
<const Value
*, unsigned>;
665 /// TheModule - The module for which we are holding slot numbers.
666 const Module
* TheModule
;
668 /// TheFunction - The function for which we are holding slot numbers.
669 const Function
* TheFunction
= nullptr;
670 bool FunctionProcessed
= false;
671 bool ShouldInitializeAllMetadata
;
673 std::function
<void(AbstractSlotTrackerStorage
*, const Module
*, bool)>
675 std::function
<void(AbstractSlotTrackerStorage
*, const Function
*, bool)>
676 ProcessFunctionHookFn
;
678 /// The summary index for which we are holding slot numbers.
679 const ModuleSummaryIndex
*TheIndex
= nullptr;
681 /// mMap - The slot map for the module level data.
685 /// fMap - The slot map for the function level data.
689 /// mdnMap - Map for MDNodes.
690 DenseMap
<const MDNode
*, unsigned> mdnMap
;
691 unsigned mdnNext
= 0;
693 /// asMap - The slot map for attribute sets.
694 DenseMap
<AttributeSet
, unsigned> asMap
;
697 /// ModulePathMap - The slot map for Module paths used in the summary index.
698 StringMap
<unsigned> ModulePathMap
;
699 unsigned ModulePathNext
= 0;
701 /// GUIDMap - The slot map for GUIDs used in the summary index.
702 DenseMap
<GlobalValue::GUID
, unsigned> GUIDMap
;
703 unsigned GUIDNext
= 0;
705 /// TypeIdMap - The slot map for type ids used in the summary index.
706 StringMap
<unsigned> TypeIdMap
;
707 unsigned TypeIdNext
= 0;
710 /// Construct from a module.
712 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
713 /// functions, giving correct numbering for metadata referenced only from
714 /// within a function (even if no functions have been initialized).
715 explicit SlotTracker(const Module
*M
,
716 bool ShouldInitializeAllMetadata
= false);
718 /// Construct from a function, starting out in incorp state.
720 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
721 /// functions, giving correct numbering for metadata referenced only from
722 /// within a function (even if no functions have been initialized).
723 explicit SlotTracker(const Function
*F
,
724 bool ShouldInitializeAllMetadata
= false);
726 /// Construct from a module summary index.
727 explicit SlotTracker(const ModuleSummaryIndex
*Index
);
729 SlotTracker(const SlotTracker
&) = delete;
730 SlotTracker
&operator=(const SlotTracker
&) = delete;
732 ~SlotTracker() = default;
735 std::function
<void(AbstractSlotTrackerStorage
*, const Module
*, bool)>);
736 void setProcessHook(std::function
<void(AbstractSlotTrackerStorage
*,
737 const Function
*, bool)>);
739 unsigned getNextMetadataSlot() override
{ return mdnNext
; }
741 void createMetadataSlot(const MDNode
*N
) override
;
743 /// Return the slot number of the specified value in it's type
744 /// plane. If something is not in the SlotTracker, return -1.
745 int getLocalSlot(const Value
*V
);
746 int getGlobalSlot(const GlobalValue
*V
);
747 int getMetadataSlot(const MDNode
*N
) override
;
748 int getAttributeGroupSlot(AttributeSet AS
);
749 int getModulePathSlot(StringRef Path
);
750 int getGUIDSlot(GlobalValue::GUID GUID
);
751 int getTypeIdSlot(StringRef Id
);
753 /// If you'd like to deal with a function instead of just a module, use
754 /// this method to get its data into the SlotTracker.
755 void incorporateFunction(const Function
*F
) {
757 FunctionProcessed
= false;
760 const Function
*getFunction() const { return TheFunction
; }
762 /// After calling incorporateFunction, use this method to remove the
763 /// most recently incorporated function from the SlotTracker. This
764 /// will reset the state of the machine back to just the module contents.
765 void purgeFunction();
767 /// MDNode map iterators.
768 using mdn_iterator
= DenseMap
<const MDNode
*, unsigned>::iterator
;
770 mdn_iterator
mdn_begin() { return mdnMap
.begin(); }
771 mdn_iterator
mdn_end() { return mdnMap
.end(); }
772 unsigned mdn_size() const { return mdnMap
.size(); }
773 bool mdn_empty() const { return mdnMap
.empty(); }
775 /// AttributeSet map iterators.
776 using as_iterator
= DenseMap
<AttributeSet
, unsigned>::iterator
;
778 as_iterator
as_begin() { return asMap
.begin(); }
779 as_iterator
as_end() { return asMap
.end(); }
780 unsigned as_size() const { return asMap
.size(); }
781 bool as_empty() const { return asMap
.empty(); }
783 /// GUID map iterators.
784 using guid_iterator
= DenseMap
<GlobalValue::GUID
, unsigned>::iterator
;
786 /// These functions do the actual initialization.
787 inline void initializeIfNeeded();
788 int initializeIndexIfNeeded();
790 // Implementation Details
792 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
793 void CreateModuleSlot(const GlobalValue
*V
);
795 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
796 void CreateMetadataSlot(const MDNode
*N
);
798 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
799 void CreateFunctionSlot(const Value
*V
);
801 /// Insert the specified AttributeSet into the slot table.
802 void CreateAttributeSetSlot(AttributeSet AS
);
804 inline void CreateModulePathSlot(StringRef Path
);
805 void CreateGUIDSlot(GlobalValue::GUID GUID
);
806 void CreateTypeIdSlot(StringRef Id
);
808 /// Add all of the module level global variables (and their initializers)
809 /// and function declarations, but not the contents of those functions.
810 void processModule();
811 // Returns number of allocated slots
814 /// Add all of the functions arguments, basic blocks, and instructions.
815 void processFunction();
817 /// Add the metadata directly attached to a GlobalObject.
818 void processGlobalObjectMetadata(const GlobalObject
&GO
);
820 /// Add all of the metadata from a function.
821 void processFunctionMetadata(const Function
&F
);
823 /// Add all of the metadata from an instruction.
824 void processInstructionMetadata(const Instruction
&I
);
827 } // end namespace llvm
829 ModuleSlotTracker::ModuleSlotTracker(SlotTracker
&Machine
, const Module
*M
,
831 : M(M
), F(F
), Machine(&Machine
) {}
833 ModuleSlotTracker::ModuleSlotTracker(const Module
*M
,
834 bool ShouldInitializeAllMetadata
)
835 : ShouldCreateStorage(M
),
836 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
), M(M
) {}
838 ModuleSlotTracker::~ModuleSlotTracker() = default;
840 SlotTracker
*ModuleSlotTracker::getMachine() {
841 if (!ShouldCreateStorage
)
844 ShouldCreateStorage
= false;
846 std::make_unique
<SlotTracker
>(M
, ShouldInitializeAllMetadata
);
847 Machine
= MachineStorage
.get();
848 if (ProcessModuleHookFn
)
849 Machine
->setProcessHook(ProcessModuleHookFn
);
850 if (ProcessFunctionHookFn
)
851 Machine
->setProcessHook(ProcessFunctionHookFn
);
855 void ModuleSlotTracker::incorporateFunction(const Function
&F
) {
856 // Using getMachine() may lazily create the slot tracker.
860 // Nothing to do if this is the right function already.
864 Machine
->purgeFunction();
865 Machine
->incorporateFunction(&F
);
869 int ModuleSlotTracker::getLocalSlot(const Value
*V
) {
870 assert(F
&& "No function incorporated");
871 return Machine
->getLocalSlot(V
);
874 void ModuleSlotTracker::setProcessHook(
875 std::function
<void(AbstractSlotTrackerStorage
*, const Module
*, bool)>
877 ProcessModuleHookFn
= Fn
;
880 void ModuleSlotTracker::setProcessHook(
881 std::function
<void(AbstractSlotTrackerStorage
*, const Function
*, bool)>
883 ProcessFunctionHookFn
= Fn
;
886 static SlotTracker
*createSlotTracker(const Value
*V
) {
887 if (const Argument
*FA
= dyn_cast
<Argument
>(V
))
888 return new SlotTracker(FA
->getParent());
890 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
))
892 return new SlotTracker(I
->getParent()->getParent());
894 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
895 return new SlotTracker(BB
->getParent());
897 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(V
))
898 return new SlotTracker(GV
->getParent());
900 if (const GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
901 return new SlotTracker(GA
->getParent());
903 if (const GlobalIFunc
*GIF
= dyn_cast
<GlobalIFunc
>(V
))
904 return new SlotTracker(GIF
->getParent());
906 if (const Function
*Func
= dyn_cast
<Function
>(V
))
907 return new SlotTracker(Func
);
913 #define ST_DEBUG(X) dbgs() << X
918 // Module level constructor. Causes the contents of the Module (sans functions)
919 // to be added to the slot table.
920 SlotTracker::SlotTracker(const Module
*M
, bool ShouldInitializeAllMetadata
)
921 : TheModule(M
), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
) {}
923 // Function level constructor. Causes the contents of the Module and the one
924 // function provided to be added to the slot table.
925 SlotTracker::SlotTracker(const Function
*F
, bool ShouldInitializeAllMetadata
)
926 : TheModule(F
? F
->getParent() : nullptr), TheFunction(F
),
927 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
) {}
929 SlotTracker::SlotTracker(const ModuleSummaryIndex
*Index
)
930 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index
) {}
932 inline void SlotTracker::initializeIfNeeded() {
935 TheModule
= nullptr; ///< Prevent re-processing next time we're called.
938 if (TheFunction
&& !FunctionProcessed
)
942 int SlotTracker::initializeIndexIfNeeded() {
945 int NumSlots
= processIndex();
946 TheIndex
= nullptr; ///< Prevent re-processing next time we're called.
950 // Iterate through all the global variables, functions, and global
951 // variable initializers and create slots for them.
952 void SlotTracker::processModule() {
953 ST_DEBUG("begin processModule!\n");
955 // Add all of the unnamed global variables to the value table.
956 for (const GlobalVariable
&Var
: TheModule
->globals()) {
958 CreateModuleSlot(&Var
);
959 processGlobalObjectMetadata(Var
);
960 auto Attrs
= Var
.getAttributes();
961 if (Attrs
.hasAttributes())
962 CreateAttributeSetSlot(Attrs
);
965 for (const GlobalAlias
&A
: TheModule
->aliases()) {
967 CreateModuleSlot(&A
);
970 for (const GlobalIFunc
&I
: TheModule
->ifuncs()) {
972 CreateModuleSlot(&I
);
975 // Add metadata used by named metadata.
976 for (const NamedMDNode
&NMD
: TheModule
->named_metadata()) {
977 for (unsigned i
= 0, e
= NMD
.getNumOperands(); i
!= e
; ++i
)
978 CreateMetadataSlot(NMD
.getOperand(i
));
981 for (const Function
&F
: *TheModule
) {
983 // Add all the unnamed functions to the table.
984 CreateModuleSlot(&F
);
986 if (ShouldInitializeAllMetadata
)
987 processFunctionMetadata(F
);
989 // Add all the function attributes to the table.
990 // FIXME: Add attributes of other objects?
991 AttributeSet FnAttrs
= F
.getAttributes().getFnAttrs();
992 if (FnAttrs
.hasAttributes())
993 CreateAttributeSetSlot(FnAttrs
);
996 if (ProcessModuleHookFn
)
997 ProcessModuleHookFn(this, TheModule
, ShouldInitializeAllMetadata
);
999 ST_DEBUG("end processModule!\n");
1002 // Process the arguments, basic blocks, and instructions of a function.
1003 void SlotTracker::processFunction() {
1004 ST_DEBUG("begin processFunction!\n");
1007 // Process function metadata if it wasn't hit at the module-level.
1008 if (!ShouldInitializeAllMetadata
)
1009 processFunctionMetadata(*TheFunction
);
1011 // Add all the function arguments with no names.
1012 for(Function::const_arg_iterator AI
= TheFunction
->arg_begin(),
1013 AE
= TheFunction
->arg_end(); AI
!= AE
; ++AI
)
1015 CreateFunctionSlot(&*AI
);
1017 ST_DEBUG("Inserting Instructions:\n");
1019 // Add all of the basic blocks and instructions with no names.
1020 for (auto &BB
: *TheFunction
) {
1022 CreateFunctionSlot(&BB
);
1024 for (auto &I
: BB
) {
1025 if (!I
.getType()->isVoidTy() && !I
.hasName())
1026 CreateFunctionSlot(&I
);
1028 // We allow direct calls to any llvm.foo function here, because the
1029 // target may not be linked into the optimizer.
1030 if (const auto *Call
= dyn_cast
<CallBase
>(&I
)) {
1031 // Add all the call attributes to the table.
1032 AttributeSet Attrs
= Call
->getAttributes().getFnAttrs();
1033 if (Attrs
.hasAttributes())
1034 CreateAttributeSetSlot(Attrs
);
1039 if (ProcessFunctionHookFn
)
1040 ProcessFunctionHookFn(this, TheFunction
, ShouldInitializeAllMetadata
);
1042 FunctionProcessed
= true;
1044 ST_DEBUG("end processFunction!\n");
1047 // Iterate through all the GUID in the index and create slots for them.
1048 int SlotTracker::processIndex() {
1049 ST_DEBUG("begin processIndex!\n");
1052 // The first block of slots are just the module ids, which start at 0 and are
1053 // assigned consecutively. Since the StringMap iteration order isn't
1054 // guaranteed, use a std::map to order by module ID before assigning slots.
1055 std::map
<uint64_t, StringRef
> ModuleIdToPathMap
;
1056 for (auto &ModPath
: TheIndex
->modulePaths())
1057 ModuleIdToPathMap
[ModPath
.second
.first
] = ModPath
.first();
1058 for (auto &ModPair
: ModuleIdToPathMap
)
1059 CreateModulePathSlot(ModPair
.second
);
1061 // Start numbering the GUIDs after the module ids.
1062 GUIDNext
= ModulePathNext
;
1064 for (auto &GlobalList
: *TheIndex
)
1065 CreateGUIDSlot(GlobalList
.first
);
1067 for (auto &TId
: TheIndex
->typeIdCompatibleVtableMap())
1068 CreateGUIDSlot(GlobalValue::getGUID(TId
.first
));
1070 // Start numbering the TypeIds after the GUIDs.
1071 TypeIdNext
= GUIDNext
;
1072 for (const auto &TID
: TheIndex
->typeIds())
1073 CreateTypeIdSlot(TID
.second
.first
);
1075 ST_DEBUG("end processIndex!\n");
1079 void SlotTracker::processGlobalObjectMetadata(const GlobalObject
&GO
) {
1080 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
1081 GO
.getAllMetadata(MDs
);
1082 for (auto &MD
: MDs
)
1083 CreateMetadataSlot(MD
.second
);
1086 void SlotTracker::processFunctionMetadata(const Function
&F
) {
1087 processGlobalObjectMetadata(F
);
1088 for (auto &BB
: F
) {
1090 processInstructionMetadata(I
);
1094 void SlotTracker::processInstructionMetadata(const Instruction
&I
) {
1095 // Process metadata used directly by intrinsics.
1096 if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
))
1097 if (Function
*F
= CI
->getCalledFunction())
1098 if (F
->isIntrinsic())
1099 for (auto &Op
: I
.operands())
1100 if (auto *V
= dyn_cast_or_null
<MetadataAsValue
>(Op
))
1101 if (MDNode
*N
= dyn_cast
<MDNode
>(V
->getMetadata()))
1102 CreateMetadataSlot(N
);
1104 // Process metadata attached to this instruction.
1105 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
1106 I
.getAllMetadata(MDs
);
1107 for (auto &MD
: MDs
)
1108 CreateMetadataSlot(MD
.second
);
1111 /// Clean up after incorporating a function. This is the only way to get out of
1112 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1113 /// incorporation state is indicated by TheFunction != 0.
1114 void SlotTracker::purgeFunction() {
1115 ST_DEBUG("begin purgeFunction!\n");
1116 fMap
.clear(); // Simply discard the function level map
1117 TheFunction
= nullptr;
1118 FunctionProcessed
= false;
1119 ST_DEBUG("end purgeFunction!\n");
1122 /// getGlobalSlot - Get the slot number of a global value.
1123 int SlotTracker::getGlobalSlot(const GlobalValue
*V
) {
1124 // Check for uninitialized state and do lazy initialization.
1125 initializeIfNeeded();
1127 // Find the value in the module map
1128 ValueMap::iterator MI
= mMap
.find(V
);
1129 return MI
== mMap
.end() ? -1 : (int)MI
->second
;
1132 void SlotTracker::setProcessHook(
1133 std::function
<void(AbstractSlotTrackerStorage
*, const Module
*, bool)>
1135 ProcessModuleHookFn
= Fn
;
1138 void SlotTracker::setProcessHook(
1139 std::function
<void(AbstractSlotTrackerStorage
*, const Function
*, bool)>
1141 ProcessFunctionHookFn
= Fn
;
1144 /// getMetadataSlot - Get the slot number of a MDNode.
1145 void SlotTracker::createMetadataSlot(const MDNode
*N
) { CreateMetadataSlot(N
); }
1147 /// getMetadataSlot - Get the slot number of a MDNode.
1148 int SlotTracker::getMetadataSlot(const MDNode
*N
) {
1149 // Check for uninitialized state and do lazy initialization.
1150 initializeIfNeeded();
1152 // Find the MDNode in the module map
1153 mdn_iterator MI
= mdnMap
.find(N
);
1154 return MI
== mdnMap
.end() ? -1 : (int)MI
->second
;
1157 /// getLocalSlot - Get the slot number for a value that is local to a function.
1158 int SlotTracker::getLocalSlot(const Value
*V
) {
1159 assert(!isa
<Constant
>(V
) && "Can't get a constant or global slot with this!");
1161 // Check for uninitialized state and do lazy initialization.
1162 initializeIfNeeded();
1164 ValueMap::iterator FI
= fMap
.find(V
);
1165 return FI
== fMap
.end() ? -1 : (int)FI
->second
;
1168 int SlotTracker::getAttributeGroupSlot(AttributeSet AS
) {
1169 // Check for uninitialized state and do lazy initialization.
1170 initializeIfNeeded();
1172 // Find the AttributeSet in the module map.
1173 as_iterator AI
= asMap
.find(AS
);
1174 return AI
== asMap
.end() ? -1 : (int)AI
->second
;
1177 int SlotTracker::getModulePathSlot(StringRef Path
) {
1178 // Check for uninitialized state and do lazy initialization.
1179 initializeIndexIfNeeded();
1181 // Find the Module path in the map
1182 auto I
= ModulePathMap
.find(Path
);
1183 return I
== ModulePathMap
.end() ? -1 : (int)I
->second
;
1186 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID
) {
1187 // Check for uninitialized state and do lazy initialization.
1188 initializeIndexIfNeeded();
1190 // Find the GUID in the map
1191 guid_iterator I
= GUIDMap
.find(GUID
);
1192 return I
== GUIDMap
.end() ? -1 : (int)I
->second
;
1195 int SlotTracker::getTypeIdSlot(StringRef Id
) {
1196 // Check for uninitialized state and do lazy initialization.
1197 initializeIndexIfNeeded();
1199 // Find the TypeId string in the map
1200 auto I
= TypeIdMap
.find(Id
);
1201 return I
== TypeIdMap
.end() ? -1 : (int)I
->second
;
1204 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1205 void SlotTracker::CreateModuleSlot(const GlobalValue
*V
) {
1206 assert(V
&& "Can't insert a null Value into SlotTracker!");
1207 assert(!V
->getType()->isVoidTy() && "Doesn't need a slot!");
1208 assert(!V
->hasName() && "Doesn't need a slot!");
1210 unsigned DestSlot
= mNext
++;
1213 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
1215 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1216 ST_DEBUG((isa
<GlobalVariable
>(V
) ? 'G' :
1217 (isa
<Function
>(V
) ? 'F' :
1218 (isa
<GlobalAlias
>(V
) ? 'A' :
1219 (isa
<GlobalIFunc
>(V
) ? 'I' : 'o')))) << "]\n");
1222 /// CreateSlot - Create a new slot for the specified value if it has no name.
1223 void SlotTracker::CreateFunctionSlot(const Value
*V
) {
1224 assert(!V
->getType()->isVoidTy() && !V
->hasName() && "Doesn't need a slot!");
1226 unsigned DestSlot
= fNext
++;
1229 // G = Global, F = Function, o = other
1230 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
1231 DestSlot
<< " [o]\n");
1234 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1235 void SlotTracker::CreateMetadataSlot(const MDNode
*N
) {
1236 assert(N
&& "Can't insert a null Value into SlotTracker!");
1238 // Don't make slots for DIExpressions or DIArgLists. We just print them inline
1240 if (isa
<DIExpression
>(N
) || isa
<DIArgList
>(N
))
1243 unsigned DestSlot
= mdnNext
;
1244 if (!mdnMap
.insert(std::make_pair(N
, DestSlot
)).second
)
1248 // Recursively add any MDNodes referenced by operands.
1249 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
)
1250 if (const MDNode
*Op
= dyn_cast_or_null
<MDNode
>(N
->getOperand(i
)))
1251 CreateMetadataSlot(Op
);
1254 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS
) {
1255 assert(AS
.hasAttributes() && "Doesn't need a slot!");
1257 as_iterator I
= asMap
.find(AS
);
1258 if (I
!= asMap
.end())
1261 unsigned DestSlot
= asNext
++;
1262 asMap
[AS
] = DestSlot
;
1265 /// Create a new slot for the specified Module
1266 void SlotTracker::CreateModulePathSlot(StringRef Path
) {
1267 ModulePathMap
[Path
] = ModulePathNext
++;
1270 /// Create a new slot for the specified GUID
1271 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID
) {
1272 GUIDMap
[GUID
] = GUIDNext
++;
1275 /// Create a new slot for the specified Id
1276 void SlotTracker::CreateTypeIdSlot(StringRef Id
) {
1277 TypeIdMap
[Id
] = TypeIdNext
++;
1280 //===----------------------------------------------------------------------===//
1281 // AsmWriter Implementation
1282 //===----------------------------------------------------------------------===//
1284 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
1285 TypePrinting
*TypePrinter
,
1286 SlotTracker
*Machine
,
1287 const Module
*Context
);
1289 static void WriteAsOperandInternal(raw_ostream
&Out
, const Metadata
*MD
,
1290 TypePrinting
*TypePrinter
,
1291 SlotTracker
*Machine
, const Module
*Context
,
1292 bool FromValue
= false);
1294 static void WriteOptimizationInfo(raw_ostream
&Out
, const User
*U
) {
1295 if (const FPMathOperator
*FPO
= dyn_cast
<const FPMathOperator
>(U
)) {
1296 // 'Fast' is an abbreviation for all fast-math-flags.
1300 if (FPO
->hasAllowReassoc())
1302 if (FPO
->hasNoNaNs())
1304 if (FPO
->hasNoInfs())
1306 if (FPO
->hasNoSignedZeros())
1308 if (FPO
->hasAllowReciprocal())
1310 if (FPO
->hasAllowContract())
1312 if (FPO
->hasApproxFunc())
1317 if (const OverflowingBinaryOperator
*OBO
=
1318 dyn_cast
<OverflowingBinaryOperator
>(U
)) {
1319 if (OBO
->hasNoUnsignedWrap())
1321 if (OBO
->hasNoSignedWrap())
1323 } else if (const PossiblyExactOperator
*Div
=
1324 dyn_cast
<PossiblyExactOperator
>(U
)) {
1327 } else if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(U
)) {
1328 if (GEP
->isInBounds())
1333 static void WriteConstantInternal(raw_ostream
&Out
, const Constant
*CV
,
1334 TypePrinting
&TypePrinter
,
1335 SlotTracker
*Machine
,
1336 const Module
*Context
) {
1337 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1338 if (CI
->getType()->isIntegerTy(1)) {
1339 Out
<< (CI
->getZExtValue() ? "true" : "false");
1342 Out
<< CI
->getValue();
1346 if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
1347 const APFloat
&APF
= CFP
->getValueAPF();
1348 if (&APF
.getSemantics() == &APFloat::IEEEsingle() ||
1349 &APF
.getSemantics() == &APFloat::IEEEdouble()) {
1350 // We would like to output the FP constant value in exponential notation,
1351 // but we cannot do this if doing so will lose precision. Check here to
1352 // make sure that we only output it in exponential format if we can parse
1353 // the value back and get the same value.
1356 bool isDouble
= &APF
.getSemantics() == &APFloat::IEEEdouble();
1357 bool isInf
= APF
.isInfinity();
1358 bool isNaN
= APF
.isNaN();
1359 if (!isInf
&& !isNaN
) {
1360 double Val
= APF
.convertToDouble();
1361 SmallString
<128> StrVal
;
1362 APF
.toString(StrVal
, 6, 0, false);
1363 // Check to make sure that the stringized number is not some string like
1364 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1365 // that the string matches the "[-+]?[0-9]" regex.
1367 assert((isDigit(StrVal
[0]) || ((StrVal
[0] == '-' || StrVal
[0] == '+') &&
1368 isDigit(StrVal
[1]))) &&
1369 "[-+]?[0-9] regex does not match!");
1370 // Reparse stringized version!
1371 if (APFloat(APFloat::IEEEdouble(), StrVal
).convertToDouble() == Val
) {
1376 // Otherwise we could not reparse it to exactly the same value, so we must
1377 // output the string in hexadecimal format! Note that loading and storing
1378 // floating point types changes the bits of NaNs on some hosts, notably
1379 // x86, so we must not use these types.
1380 static_assert(sizeof(double) == sizeof(uint64_t),
1381 "assuming that double is 64 bits!");
1383 // Floats are represented in ASCII IR as double, convert.
1384 // FIXME: We should allow 32-bit hex float and remove this.
1386 // A signaling NaN is quieted on conversion, so we need to recreate the
1387 // expected value after convert (quiet bit of the payload is clear).
1388 bool IsSNAN
= apf
.isSignaling();
1389 apf
.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven
,
1392 APInt Payload
= apf
.bitcastToAPInt();
1393 apf
= APFloat::getSNaN(APFloat::IEEEdouble(), apf
.isNegative(),
1397 Out
<< format_hex(apf
.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1401 // Either half, bfloat or some form of long double.
1402 // These appear as a magic letter identifying the type, then a
1403 // fixed number of hex digits.
1405 APInt API
= APF
.bitcastToAPInt();
1406 if (&APF
.getSemantics() == &APFloat::x87DoubleExtended()) {
1408 Out
<< format_hex_no_prefix(API
.getHiBits(16).getZExtValue(), 4,
1410 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1413 } else if (&APF
.getSemantics() == &APFloat::IEEEquad()) {
1415 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1417 Out
<< format_hex_no_prefix(API
.getHiBits(64).getZExtValue(), 16,
1419 } else if (&APF
.getSemantics() == &APFloat::PPCDoubleDouble()) {
1421 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1423 Out
<< format_hex_no_prefix(API
.getHiBits(64).getZExtValue(), 16,
1425 } else if (&APF
.getSemantics() == &APFloat::IEEEhalf()) {
1427 Out
<< format_hex_no_prefix(API
.getZExtValue(), 4,
1429 } else if (&APF
.getSemantics() == &APFloat::BFloat()) {
1431 Out
<< format_hex_no_prefix(API
.getZExtValue(), 4,
1434 llvm_unreachable("Unsupported floating point type");
1438 if (isa
<ConstantAggregateZero
>(CV
)) {
1439 Out
<< "zeroinitializer";
1443 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
)) {
1444 Out
<< "blockaddress(";
1445 WriteAsOperandInternal(Out
, BA
->getFunction(), &TypePrinter
, Machine
,
1448 WriteAsOperandInternal(Out
, BA
->getBasicBlock(), &TypePrinter
, Machine
,
1454 if (const auto *Equiv
= dyn_cast
<DSOLocalEquivalent
>(CV
)) {
1455 Out
<< "dso_local_equivalent ";
1456 WriteAsOperandInternal(Out
, Equiv
->getGlobalValue(), &TypePrinter
, Machine
,
1461 if (const ConstantArray
*CA
= dyn_cast
<ConstantArray
>(CV
)) {
1462 Type
*ETy
= CA
->getType()->getElementType();
1464 TypePrinter
.print(ETy
, Out
);
1466 WriteAsOperandInternal(Out
, CA
->getOperand(0),
1467 &TypePrinter
, Machine
,
1469 for (unsigned i
= 1, e
= CA
->getNumOperands(); i
!= e
; ++i
) {
1471 TypePrinter
.print(ETy
, Out
);
1473 WriteAsOperandInternal(Out
, CA
->getOperand(i
), &TypePrinter
, Machine
,
1480 if (const ConstantDataArray
*CA
= dyn_cast
<ConstantDataArray
>(CV
)) {
1481 // As a special case, print the array as a string if it is an array of
1482 // i8 with ConstantInt values.
1483 if (CA
->isString()) {
1485 printEscapedString(CA
->getAsString(), Out
);
1490 Type
*ETy
= CA
->getType()->getElementType();
1492 TypePrinter
.print(ETy
, Out
);
1494 WriteAsOperandInternal(Out
, CA
->getElementAsConstant(0),
1495 &TypePrinter
, Machine
,
1497 for (unsigned i
= 1, e
= CA
->getNumElements(); i
!= e
; ++i
) {
1499 TypePrinter
.print(ETy
, Out
);
1501 WriteAsOperandInternal(Out
, CA
->getElementAsConstant(i
), &TypePrinter
,
1508 if (const ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(CV
)) {
1509 if (CS
->getType()->isPacked())
1512 unsigned N
= CS
->getNumOperands();
1515 TypePrinter
.print(CS
->getOperand(0)->getType(), Out
);
1518 WriteAsOperandInternal(Out
, CS
->getOperand(0), &TypePrinter
, Machine
,
1521 for (unsigned i
= 1; i
< N
; i
++) {
1523 TypePrinter
.print(CS
->getOperand(i
)->getType(), Out
);
1526 WriteAsOperandInternal(Out
, CS
->getOperand(i
), &TypePrinter
, Machine
,
1533 if (CS
->getType()->isPacked())
1538 if (isa
<ConstantVector
>(CV
) || isa
<ConstantDataVector
>(CV
)) {
1539 auto *CVVTy
= cast
<FixedVectorType
>(CV
->getType());
1540 Type
*ETy
= CVVTy
->getElementType();
1542 TypePrinter
.print(ETy
, Out
);
1544 WriteAsOperandInternal(Out
, CV
->getAggregateElement(0U), &TypePrinter
,
1546 for (unsigned i
= 1, e
= CVVTy
->getNumElements(); i
!= e
; ++i
) {
1548 TypePrinter
.print(ETy
, Out
);
1550 WriteAsOperandInternal(Out
, CV
->getAggregateElement(i
), &TypePrinter
,
1557 if (isa
<ConstantPointerNull
>(CV
)) {
1562 if (isa
<ConstantTokenNone
>(CV
)) {
1567 if (isa
<PoisonValue
>(CV
)) {
1572 if (isa
<UndefValue
>(CV
)) {
1577 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
1578 Out
<< CE
->getOpcodeName();
1579 WriteOptimizationInfo(Out
, CE
);
1580 if (CE
->isCompare())
1581 Out
<< ' ' << CmpInst::getPredicateName(
1582 static_cast<CmpInst::Predicate
>(CE
->getPredicate()));
1585 Optional
<unsigned> InRangeOp
;
1586 if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(CE
)) {
1587 TypePrinter
.print(GEP
->getSourceElementType(), Out
);
1589 InRangeOp
= GEP
->getInRangeIndex();
1594 for (User::const_op_iterator OI
=CE
->op_begin(); OI
!= CE
->op_end(); ++OI
) {
1595 if (InRangeOp
&& unsigned(OI
- CE
->op_begin()) == *InRangeOp
)
1597 TypePrinter
.print((*OI
)->getType(), Out
);
1599 WriteAsOperandInternal(Out
, *OI
, &TypePrinter
, Machine
, Context
);
1600 if (OI
+1 != CE
->op_end())
1604 if (CE
->hasIndices()) {
1605 ArrayRef
<unsigned> Indices
= CE
->getIndices();
1606 for (unsigned i
= 0, e
= Indices
.size(); i
!= e
; ++i
)
1607 Out
<< ", " << Indices
[i
];
1612 TypePrinter
.print(CE
->getType(), Out
);
1615 if (CE
->getOpcode() == Instruction::ShuffleVector
)
1616 PrintShuffleMask(Out
, CE
->getType(), CE
->getShuffleMask());
1622 Out
<< "<placeholder or erroneous Constant>";
1625 static void writeMDTuple(raw_ostream
&Out
, const MDTuple
*Node
,
1626 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1627 const Module
*Context
) {
1629 for (unsigned mi
= 0, me
= Node
->getNumOperands(); mi
!= me
; ++mi
) {
1630 const Metadata
*MD
= Node
->getOperand(mi
);
1633 else if (auto *MDV
= dyn_cast
<ValueAsMetadata
>(MD
)) {
1634 Value
*V
= MDV
->getValue();
1635 TypePrinter
->print(V
->getType(), Out
);
1637 WriteAsOperandInternal(Out
, V
, TypePrinter
, Machine
, Context
);
1639 WriteAsOperandInternal(Out
, MD
, TypePrinter
, Machine
, Context
);
1650 struct FieldSeparator
{
1654 FieldSeparator(const char *Sep
= ", ") : Sep(Sep
) {}
1657 raw_ostream
&operator<<(raw_ostream
&OS
, FieldSeparator
&FS
) {
1662 return OS
<< FS
.Sep
;
1665 struct MDFieldPrinter
{
1668 TypePrinting
*TypePrinter
= nullptr;
1669 SlotTracker
*Machine
= nullptr;
1670 const Module
*Context
= nullptr;
1672 explicit MDFieldPrinter(raw_ostream
&Out
) : Out(Out
) {}
1673 MDFieldPrinter(raw_ostream
&Out
, TypePrinting
*TypePrinter
,
1674 SlotTracker
*Machine
, const Module
*Context
)
1675 : Out(Out
), TypePrinter(TypePrinter
), Machine(Machine
), Context(Context
) {
1678 void printTag(const DINode
*N
);
1679 void printMacinfoType(const DIMacroNode
*N
);
1680 void printChecksum(const DIFile::ChecksumInfo
<StringRef
> &N
);
1681 void printString(StringRef Name
, StringRef Value
,
1682 bool ShouldSkipEmpty
= true);
1683 void printMetadata(StringRef Name
, const Metadata
*MD
,
1684 bool ShouldSkipNull
= true);
1685 template <class IntTy
>
1686 void printInt(StringRef Name
, IntTy Int
, bool ShouldSkipZero
= true);
1687 void printAPInt(StringRef Name
, const APInt
&Int
, bool IsUnsigned
,
1688 bool ShouldSkipZero
);
1689 void printBool(StringRef Name
, bool Value
, Optional
<bool> Default
= None
);
1690 void printDIFlags(StringRef Name
, DINode::DIFlags Flags
);
1691 void printDISPFlags(StringRef Name
, DISubprogram::DISPFlags Flags
);
1692 template <class IntTy
, class Stringifier
>
1693 void printDwarfEnum(StringRef Name
, IntTy Value
, Stringifier toString
,
1694 bool ShouldSkipZero
= true);
1695 void printEmissionKind(StringRef Name
, DICompileUnit::DebugEmissionKind EK
);
1696 void printNameTableKind(StringRef Name
,
1697 DICompileUnit::DebugNameTableKind NTK
);
1700 } // end anonymous namespace
1702 void MDFieldPrinter::printTag(const DINode
*N
) {
1703 Out
<< FS
<< "tag: ";
1704 auto Tag
= dwarf::TagString(N
->getTag());
1711 void MDFieldPrinter::printMacinfoType(const DIMacroNode
*N
) {
1712 Out
<< FS
<< "type: ";
1713 auto Type
= dwarf::MacinfoString(N
->getMacinfoType());
1717 Out
<< N
->getMacinfoType();
1720 void MDFieldPrinter::printChecksum(
1721 const DIFile::ChecksumInfo
<StringRef
> &Checksum
) {
1722 Out
<< FS
<< "checksumkind: " << Checksum
.getKindAsString();
1723 printString("checksum", Checksum
.Value
, /* ShouldSkipEmpty */ false);
1726 void MDFieldPrinter::printString(StringRef Name
, StringRef Value
,
1727 bool ShouldSkipEmpty
) {
1728 if (ShouldSkipEmpty
&& Value
.empty())
1731 Out
<< FS
<< Name
<< ": \"";
1732 printEscapedString(Value
, Out
);
1736 static void writeMetadataAsOperand(raw_ostream
&Out
, const Metadata
*MD
,
1737 TypePrinting
*TypePrinter
,
1738 SlotTracker
*Machine
,
1739 const Module
*Context
) {
1744 WriteAsOperandInternal(Out
, MD
, TypePrinter
, Machine
, Context
);
1747 void MDFieldPrinter::printMetadata(StringRef Name
, const Metadata
*MD
,
1748 bool ShouldSkipNull
) {
1749 if (ShouldSkipNull
&& !MD
)
1752 Out
<< FS
<< Name
<< ": ";
1753 writeMetadataAsOperand(Out
, MD
, TypePrinter
, Machine
, Context
);
1756 template <class IntTy
>
1757 void MDFieldPrinter::printInt(StringRef Name
, IntTy Int
, bool ShouldSkipZero
) {
1758 if (ShouldSkipZero
&& !Int
)
1761 Out
<< FS
<< Name
<< ": " << Int
;
1764 void MDFieldPrinter::printAPInt(StringRef Name
, const APInt
&Int
,
1765 bool IsUnsigned
, bool ShouldSkipZero
) {
1766 if (ShouldSkipZero
&& Int
.isNullValue())
1769 Out
<< FS
<< Name
<< ": ";
1770 Int
.print(Out
, !IsUnsigned
);
1773 void MDFieldPrinter::printBool(StringRef Name
, bool Value
,
1774 Optional
<bool> Default
) {
1775 if (Default
&& Value
== *Default
)
1777 Out
<< FS
<< Name
<< ": " << (Value
? "true" : "false");
1780 void MDFieldPrinter::printDIFlags(StringRef Name
, DINode::DIFlags Flags
) {
1784 Out
<< FS
<< Name
<< ": ";
1786 SmallVector
<DINode::DIFlags
, 8> SplitFlags
;
1787 auto Extra
= DINode::splitFlags(Flags
, SplitFlags
);
1789 FieldSeparator
FlagsFS(" | ");
1790 for (auto F
: SplitFlags
) {
1791 auto StringF
= DINode::getFlagString(F
);
1792 assert(!StringF
.empty() && "Expected valid flag");
1793 Out
<< FlagsFS
<< StringF
;
1795 if (Extra
|| SplitFlags
.empty())
1796 Out
<< FlagsFS
<< Extra
;
1799 void MDFieldPrinter::printDISPFlags(StringRef Name
,
1800 DISubprogram::DISPFlags Flags
) {
1801 // Always print this field, because no flags in the IR at all will be
1802 // interpreted as old-style isDefinition: true.
1803 Out
<< FS
<< Name
<< ": ";
1810 SmallVector
<DISubprogram::DISPFlags
, 8> SplitFlags
;
1811 auto Extra
= DISubprogram::splitFlags(Flags
, SplitFlags
);
1813 FieldSeparator
FlagsFS(" | ");
1814 for (auto F
: SplitFlags
) {
1815 auto StringF
= DISubprogram::getFlagString(F
);
1816 assert(!StringF
.empty() && "Expected valid flag");
1817 Out
<< FlagsFS
<< StringF
;
1819 if (Extra
|| SplitFlags
.empty())
1820 Out
<< FlagsFS
<< Extra
;
1823 void MDFieldPrinter::printEmissionKind(StringRef Name
,
1824 DICompileUnit::DebugEmissionKind EK
) {
1825 Out
<< FS
<< Name
<< ": " << DICompileUnit::emissionKindString(EK
);
1828 void MDFieldPrinter::printNameTableKind(StringRef Name
,
1829 DICompileUnit::DebugNameTableKind NTK
) {
1830 if (NTK
== DICompileUnit::DebugNameTableKind::Default
)
1832 Out
<< FS
<< Name
<< ": " << DICompileUnit::nameTableKindString(NTK
);
1835 template <class IntTy
, class Stringifier
>
1836 void MDFieldPrinter::printDwarfEnum(StringRef Name
, IntTy Value
,
1837 Stringifier toString
, bool ShouldSkipZero
) {
1841 Out
<< FS
<< Name
<< ": ";
1842 auto S
= toString(Value
);
1849 static void writeGenericDINode(raw_ostream
&Out
, const GenericDINode
*N
,
1850 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1851 const Module
*Context
) {
1852 Out
<< "!GenericDINode(";
1853 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1854 Printer
.printTag(N
);
1855 Printer
.printString("header", N
->getHeader());
1856 if (N
->getNumDwarfOperands()) {
1857 Out
<< Printer
.FS
<< "operands: {";
1859 for (auto &I
: N
->dwarf_operands()) {
1861 writeMetadataAsOperand(Out
, I
, TypePrinter
, Machine
, Context
);
1868 static void writeDILocation(raw_ostream
&Out
, const DILocation
*DL
,
1869 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1870 const Module
*Context
) {
1871 Out
<< "!DILocation(";
1872 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1873 // Always output the line, since 0 is a relevant and important value for it.
1874 Printer
.printInt("line", DL
->getLine(), /* ShouldSkipZero */ false);
1875 Printer
.printInt("column", DL
->getColumn());
1876 Printer
.printMetadata("scope", DL
->getRawScope(), /* ShouldSkipNull */ false);
1877 Printer
.printMetadata("inlinedAt", DL
->getRawInlinedAt());
1878 Printer
.printBool("isImplicitCode", DL
->isImplicitCode(),
1879 /* Default */ false);
1883 static void writeDISubrange(raw_ostream
&Out
, const DISubrange
*N
,
1884 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1885 const Module
*Context
) {
1886 Out
<< "!DISubrange(";
1887 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1889 auto *Count
= N
->getRawCountNode();
1890 if (auto *CE
= dyn_cast_or_null
<ConstantAsMetadata
>(Count
)) {
1891 auto *CV
= cast
<ConstantInt
>(CE
->getValue());
1892 Printer
.printInt("count", CV
->getSExtValue(),
1893 /* ShouldSkipZero */ false);
1895 Printer
.printMetadata("count", Count
, /*ShouldSkipNull */ true);
1897 // A lowerBound of constant 0 should not be skipped, since it is different
1898 // from an unspecified lower bound (= nullptr).
1899 auto *LBound
= N
->getRawLowerBound();
1900 if (auto *LE
= dyn_cast_or_null
<ConstantAsMetadata
>(LBound
)) {
1901 auto *LV
= cast
<ConstantInt
>(LE
->getValue());
1902 Printer
.printInt("lowerBound", LV
->getSExtValue(),
1903 /* ShouldSkipZero */ false);
1905 Printer
.printMetadata("lowerBound", LBound
, /*ShouldSkipNull */ true);
1907 auto *UBound
= N
->getRawUpperBound();
1908 if (auto *UE
= dyn_cast_or_null
<ConstantAsMetadata
>(UBound
)) {
1909 auto *UV
= cast
<ConstantInt
>(UE
->getValue());
1910 Printer
.printInt("upperBound", UV
->getSExtValue(),
1911 /* ShouldSkipZero */ false);
1913 Printer
.printMetadata("upperBound", UBound
, /*ShouldSkipNull */ true);
1915 auto *Stride
= N
->getRawStride();
1916 if (auto *SE
= dyn_cast_or_null
<ConstantAsMetadata
>(Stride
)) {
1917 auto *SV
= cast
<ConstantInt
>(SE
->getValue());
1918 Printer
.printInt("stride", SV
->getSExtValue(), /* ShouldSkipZero */ false);
1920 Printer
.printMetadata("stride", Stride
, /*ShouldSkipNull */ true);
1925 static void writeDIGenericSubrange(raw_ostream
&Out
, const DIGenericSubrange
*N
,
1926 TypePrinting
*TypePrinter
,
1927 SlotTracker
*Machine
,
1928 const Module
*Context
) {
1929 Out
<< "!DIGenericSubrange(";
1930 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1932 auto IsConstant
= [&](Metadata
*Bound
) -> bool {
1933 if (auto *BE
= dyn_cast_or_null
<DIExpression
>(Bound
)) {
1934 return BE
->isConstant() &&
1935 DIExpression::SignedOrUnsignedConstant::SignedConstant
==
1941 auto GetConstant
= [&](Metadata
*Bound
) -> int64_t {
1942 assert(IsConstant(Bound
) && "Expected constant");
1943 auto *BE
= dyn_cast_or_null
<DIExpression
>(Bound
);
1944 return static_cast<int64_t>(BE
->getElement(1));
1947 auto *Count
= N
->getRawCountNode();
1948 if (IsConstant(Count
))
1949 Printer
.printInt("count", GetConstant(Count
),
1950 /* ShouldSkipZero */ false);
1952 Printer
.printMetadata("count", Count
, /*ShouldSkipNull */ true);
1954 auto *LBound
= N
->getRawLowerBound();
1955 if (IsConstant(LBound
))
1956 Printer
.printInt("lowerBound", GetConstant(LBound
),
1957 /* ShouldSkipZero */ false);
1959 Printer
.printMetadata("lowerBound", LBound
, /*ShouldSkipNull */ true);
1961 auto *UBound
= N
->getRawUpperBound();
1962 if (IsConstant(UBound
))
1963 Printer
.printInt("upperBound", GetConstant(UBound
),
1964 /* ShouldSkipZero */ false);
1966 Printer
.printMetadata("upperBound", UBound
, /*ShouldSkipNull */ true);
1968 auto *Stride
= N
->getRawStride();
1969 if (IsConstant(Stride
))
1970 Printer
.printInt("stride", GetConstant(Stride
),
1971 /* ShouldSkipZero */ false);
1973 Printer
.printMetadata("stride", Stride
, /*ShouldSkipNull */ true);
1978 static void writeDIEnumerator(raw_ostream
&Out
, const DIEnumerator
*N
,
1979 TypePrinting
*, SlotTracker
*, const Module
*) {
1980 Out
<< "!DIEnumerator(";
1981 MDFieldPrinter
Printer(Out
);
1982 Printer
.printString("name", N
->getName(), /* ShouldSkipEmpty */ false);
1983 Printer
.printAPInt("value", N
->getValue(), N
->isUnsigned(),
1984 /*ShouldSkipZero=*/false);
1985 if (N
->isUnsigned())
1986 Printer
.printBool("isUnsigned", true);
1990 static void writeDIBasicType(raw_ostream
&Out
, const DIBasicType
*N
,
1991 TypePrinting
*, SlotTracker
*, const Module
*) {
1992 Out
<< "!DIBasicType(";
1993 MDFieldPrinter
Printer(Out
);
1994 if (N
->getTag() != dwarf::DW_TAG_base_type
)
1995 Printer
.printTag(N
);
1996 Printer
.printString("name", N
->getName());
1997 Printer
.printInt("size", N
->getSizeInBits());
1998 Printer
.printInt("align", N
->getAlignInBits());
1999 Printer
.printDwarfEnum("encoding", N
->getEncoding(),
2000 dwarf::AttributeEncodingString
);
2001 Printer
.printDIFlags("flags", N
->getFlags());
2005 static void writeDIStringType(raw_ostream
&Out
, const DIStringType
*N
,
2006 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2007 const Module
*Context
) {
2008 Out
<< "!DIStringType(";
2009 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2010 if (N
->getTag() != dwarf::DW_TAG_string_type
)
2011 Printer
.printTag(N
);
2012 Printer
.printString("name", N
->getName());
2013 Printer
.printMetadata("stringLength", N
->getRawStringLength());
2014 Printer
.printMetadata("stringLengthExpression", N
->getRawStringLengthExp());
2015 Printer
.printInt("size", N
->getSizeInBits());
2016 Printer
.printInt("align", N
->getAlignInBits());
2017 Printer
.printDwarfEnum("encoding", N
->getEncoding(),
2018 dwarf::AttributeEncodingString
);
2022 static void writeDIDerivedType(raw_ostream
&Out
, const DIDerivedType
*N
,
2023 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2024 const Module
*Context
) {
2025 Out
<< "!DIDerivedType(";
2026 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2027 Printer
.printTag(N
);
2028 Printer
.printString("name", N
->getName());
2029 Printer
.printMetadata("scope", N
->getRawScope());
2030 Printer
.printMetadata("file", N
->getRawFile());
2031 Printer
.printInt("line", N
->getLine());
2032 Printer
.printMetadata("baseType", N
->getRawBaseType(),
2033 /* ShouldSkipNull */ false);
2034 Printer
.printInt("size", N
->getSizeInBits());
2035 Printer
.printInt("align", N
->getAlignInBits());
2036 Printer
.printInt("offset", N
->getOffsetInBits());
2037 Printer
.printDIFlags("flags", N
->getFlags());
2038 Printer
.printMetadata("extraData", N
->getRawExtraData());
2039 if (const auto &DWARFAddressSpace
= N
->getDWARFAddressSpace())
2040 Printer
.printInt("dwarfAddressSpace", *DWARFAddressSpace
,
2041 /* ShouldSkipZero */ false);
2042 Printer
.printMetadata("annotations", N
->getRawAnnotations());
2046 static void writeDICompositeType(raw_ostream
&Out
, const DICompositeType
*N
,
2047 TypePrinting
*TypePrinter
,
2048 SlotTracker
*Machine
, const Module
*Context
) {
2049 Out
<< "!DICompositeType(";
2050 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2051 Printer
.printTag(N
);
2052 Printer
.printString("name", N
->getName());
2053 Printer
.printMetadata("scope", N
->getRawScope());
2054 Printer
.printMetadata("file", N
->getRawFile());
2055 Printer
.printInt("line", N
->getLine());
2056 Printer
.printMetadata("baseType", N
->getRawBaseType());
2057 Printer
.printInt("size", N
->getSizeInBits());
2058 Printer
.printInt("align", N
->getAlignInBits());
2059 Printer
.printInt("offset", N
->getOffsetInBits());
2060 Printer
.printDIFlags("flags", N
->getFlags());
2061 Printer
.printMetadata("elements", N
->getRawElements());
2062 Printer
.printDwarfEnum("runtimeLang", N
->getRuntimeLang(),
2063 dwarf::LanguageString
);
2064 Printer
.printMetadata("vtableHolder", N
->getRawVTableHolder());
2065 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
2066 Printer
.printString("identifier", N
->getIdentifier());
2067 Printer
.printMetadata("discriminator", N
->getRawDiscriminator());
2068 Printer
.printMetadata("dataLocation", N
->getRawDataLocation());
2069 Printer
.printMetadata("associated", N
->getRawAssociated());
2070 Printer
.printMetadata("allocated", N
->getRawAllocated());
2071 if (auto *RankConst
= N
->getRankConst())
2072 Printer
.printInt("rank", RankConst
->getSExtValue(),
2073 /* ShouldSkipZero */ false);
2075 Printer
.printMetadata("rank", N
->getRawRank(), /*ShouldSkipNull */ true);
2076 Printer
.printMetadata("annotations", N
->getRawAnnotations());
2080 static void writeDISubroutineType(raw_ostream
&Out
, const DISubroutineType
*N
,
2081 TypePrinting
*TypePrinter
,
2082 SlotTracker
*Machine
, const Module
*Context
) {
2083 Out
<< "!DISubroutineType(";
2084 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2085 Printer
.printDIFlags("flags", N
->getFlags());
2086 Printer
.printDwarfEnum("cc", N
->getCC(), dwarf::ConventionString
);
2087 Printer
.printMetadata("types", N
->getRawTypeArray(),
2088 /* ShouldSkipNull */ false);
2092 static void writeDIFile(raw_ostream
&Out
, const DIFile
*N
, TypePrinting
*,
2093 SlotTracker
*, const Module
*) {
2095 MDFieldPrinter
Printer(Out
);
2096 Printer
.printString("filename", N
->getFilename(),
2097 /* ShouldSkipEmpty */ false);
2098 Printer
.printString("directory", N
->getDirectory(),
2099 /* ShouldSkipEmpty */ false);
2100 // Print all values for checksum together, or not at all.
2101 if (N
->getChecksum())
2102 Printer
.printChecksum(*N
->getChecksum());
2103 Printer
.printString("source", N
->getSource().getValueOr(StringRef()),
2104 /* ShouldSkipEmpty */ true);
2108 static void writeDICompileUnit(raw_ostream
&Out
, const DICompileUnit
*N
,
2109 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2110 const Module
*Context
) {
2111 Out
<< "!DICompileUnit(";
2112 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2113 Printer
.printDwarfEnum("language", N
->getSourceLanguage(),
2114 dwarf::LanguageString
, /* ShouldSkipZero */ false);
2115 Printer
.printMetadata("file", N
->getRawFile(), /* ShouldSkipNull */ false);
2116 Printer
.printString("producer", N
->getProducer());
2117 Printer
.printBool("isOptimized", N
->isOptimized());
2118 Printer
.printString("flags", N
->getFlags());
2119 Printer
.printInt("runtimeVersion", N
->getRuntimeVersion(),
2120 /* ShouldSkipZero */ false);
2121 Printer
.printString("splitDebugFilename", N
->getSplitDebugFilename());
2122 Printer
.printEmissionKind("emissionKind", N
->getEmissionKind());
2123 Printer
.printMetadata("enums", N
->getRawEnumTypes());
2124 Printer
.printMetadata("retainedTypes", N
->getRawRetainedTypes());
2125 Printer
.printMetadata("globals", N
->getRawGlobalVariables());
2126 Printer
.printMetadata("imports", N
->getRawImportedEntities());
2127 Printer
.printMetadata("macros", N
->getRawMacros());
2128 Printer
.printInt("dwoId", N
->getDWOId());
2129 Printer
.printBool("splitDebugInlining", N
->getSplitDebugInlining(), true);
2130 Printer
.printBool("debugInfoForProfiling", N
->getDebugInfoForProfiling(),
2132 Printer
.printNameTableKind("nameTableKind", N
->getNameTableKind());
2133 Printer
.printBool("rangesBaseAddress", N
->getRangesBaseAddress(), false);
2134 Printer
.printString("sysroot", N
->getSysRoot());
2135 Printer
.printString("sdk", N
->getSDK());
2139 static void writeDISubprogram(raw_ostream
&Out
, const DISubprogram
*N
,
2140 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2141 const Module
*Context
) {
2142 Out
<< "!DISubprogram(";
2143 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2144 Printer
.printString("name", N
->getName());
2145 Printer
.printString("linkageName", N
->getLinkageName());
2146 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2147 Printer
.printMetadata("file", N
->getRawFile());
2148 Printer
.printInt("line", N
->getLine());
2149 Printer
.printMetadata("type", N
->getRawType());
2150 Printer
.printInt("scopeLine", N
->getScopeLine());
2151 Printer
.printMetadata("containingType", N
->getRawContainingType());
2152 if (N
->getVirtuality() != dwarf::DW_VIRTUALITY_none
||
2153 N
->getVirtualIndex() != 0)
2154 Printer
.printInt("virtualIndex", N
->getVirtualIndex(), false);
2155 Printer
.printInt("thisAdjustment", N
->getThisAdjustment());
2156 Printer
.printDIFlags("flags", N
->getFlags());
2157 Printer
.printDISPFlags("spFlags", N
->getSPFlags());
2158 Printer
.printMetadata("unit", N
->getRawUnit());
2159 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
2160 Printer
.printMetadata("declaration", N
->getRawDeclaration());
2161 Printer
.printMetadata("retainedNodes", N
->getRawRetainedNodes());
2162 Printer
.printMetadata("thrownTypes", N
->getRawThrownTypes());
2166 static void writeDILexicalBlock(raw_ostream
&Out
, const DILexicalBlock
*N
,
2167 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2168 const Module
*Context
) {
2169 Out
<< "!DILexicalBlock(";
2170 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2171 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2172 Printer
.printMetadata("file", N
->getRawFile());
2173 Printer
.printInt("line", N
->getLine());
2174 Printer
.printInt("column", N
->getColumn());
2178 static void writeDILexicalBlockFile(raw_ostream
&Out
,
2179 const DILexicalBlockFile
*N
,
2180 TypePrinting
*TypePrinter
,
2181 SlotTracker
*Machine
,
2182 const Module
*Context
) {
2183 Out
<< "!DILexicalBlockFile(";
2184 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2185 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2186 Printer
.printMetadata("file", N
->getRawFile());
2187 Printer
.printInt("discriminator", N
->getDiscriminator(),
2188 /* ShouldSkipZero */ false);
2192 static void writeDINamespace(raw_ostream
&Out
, const DINamespace
*N
,
2193 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2194 const Module
*Context
) {
2195 Out
<< "!DINamespace(";
2196 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2197 Printer
.printString("name", N
->getName());
2198 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2199 Printer
.printBool("exportSymbols", N
->getExportSymbols(), false);
2203 static void writeDICommonBlock(raw_ostream
&Out
, const DICommonBlock
*N
,
2204 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2205 const Module
*Context
) {
2206 Out
<< "!DICommonBlock(";
2207 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2208 Printer
.printMetadata("scope", N
->getRawScope(), false);
2209 Printer
.printMetadata("declaration", N
->getRawDecl(), false);
2210 Printer
.printString("name", N
->getName());
2211 Printer
.printMetadata("file", N
->getRawFile());
2212 Printer
.printInt("line", N
->getLineNo());
2216 static void writeDIMacro(raw_ostream
&Out
, const DIMacro
*N
,
2217 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2218 const Module
*Context
) {
2220 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2221 Printer
.printMacinfoType(N
);
2222 Printer
.printInt("line", N
->getLine());
2223 Printer
.printString("name", N
->getName());
2224 Printer
.printString("value", N
->getValue());
2228 static void writeDIMacroFile(raw_ostream
&Out
, const DIMacroFile
*N
,
2229 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2230 const Module
*Context
) {
2231 Out
<< "!DIMacroFile(";
2232 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2233 Printer
.printInt("line", N
->getLine());
2234 Printer
.printMetadata("file", N
->getRawFile(), /* ShouldSkipNull */ false);
2235 Printer
.printMetadata("nodes", N
->getRawElements());
2239 static void writeDIModule(raw_ostream
&Out
, const DIModule
*N
,
2240 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2241 const Module
*Context
) {
2242 Out
<< "!DIModule(";
2243 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2244 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2245 Printer
.printString("name", N
->getName());
2246 Printer
.printString("configMacros", N
->getConfigurationMacros());
2247 Printer
.printString("includePath", N
->getIncludePath());
2248 Printer
.printString("apinotes", N
->getAPINotesFile());
2249 Printer
.printMetadata("file", N
->getRawFile());
2250 Printer
.printInt("line", N
->getLineNo());
2251 Printer
.printBool("isDecl", N
->getIsDecl(), /* Default */ false);
2256 static void writeDITemplateTypeParameter(raw_ostream
&Out
,
2257 const DITemplateTypeParameter
*N
,
2258 TypePrinting
*TypePrinter
,
2259 SlotTracker
*Machine
,
2260 const Module
*Context
) {
2261 Out
<< "!DITemplateTypeParameter(";
2262 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2263 Printer
.printString("name", N
->getName());
2264 Printer
.printMetadata("type", N
->getRawType(), /* ShouldSkipNull */ false);
2265 Printer
.printBool("defaulted", N
->isDefault(), /* Default= */ false);
2269 static void writeDITemplateValueParameter(raw_ostream
&Out
,
2270 const DITemplateValueParameter
*N
,
2271 TypePrinting
*TypePrinter
,
2272 SlotTracker
*Machine
,
2273 const Module
*Context
) {
2274 Out
<< "!DITemplateValueParameter(";
2275 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2276 if (N
->getTag() != dwarf::DW_TAG_template_value_parameter
)
2277 Printer
.printTag(N
);
2278 Printer
.printString("name", N
->getName());
2279 Printer
.printMetadata("type", N
->getRawType());
2280 Printer
.printBool("defaulted", N
->isDefault(), /* Default= */ false);
2281 Printer
.printMetadata("value", N
->getValue(), /* ShouldSkipNull */ false);
2285 static void writeDIGlobalVariable(raw_ostream
&Out
, const DIGlobalVariable
*N
,
2286 TypePrinting
*TypePrinter
,
2287 SlotTracker
*Machine
, const Module
*Context
) {
2288 Out
<< "!DIGlobalVariable(";
2289 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2290 Printer
.printString("name", N
->getName());
2291 Printer
.printString("linkageName", N
->getLinkageName());
2292 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2293 Printer
.printMetadata("file", N
->getRawFile());
2294 Printer
.printInt("line", N
->getLine());
2295 Printer
.printMetadata("type", N
->getRawType());
2296 Printer
.printBool("isLocal", N
->isLocalToUnit());
2297 Printer
.printBool("isDefinition", N
->isDefinition());
2298 Printer
.printMetadata("declaration", N
->getRawStaticDataMemberDeclaration());
2299 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
2300 Printer
.printInt("align", N
->getAlignInBits());
2304 static void writeDILocalVariable(raw_ostream
&Out
, const DILocalVariable
*N
,
2305 TypePrinting
*TypePrinter
,
2306 SlotTracker
*Machine
, const Module
*Context
) {
2307 Out
<< "!DILocalVariable(";
2308 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2309 Printer
.printString("name", N
->getName());
2310 Printer
.printInt("arg", N
->getArg());
2311 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2312 Printer
.printMetadata("file", N
->getRawFile());
2313 Printer
.printInt("line", N
->getLine());
2314 Printer
.printMetadata("type", N
->getRawType());
2315 Printer
.printDIFlags("flags", N
->getFlags());
2316 Printer
.printInt("align", N
->getAlignInBits());
2320 static void writeDILabel(raw_ostream
&Out
, const DILabel
*N
,
2321 TypePrinting
*TypePrinter
,
2322 SlotTracker
*Machine
, const Module
*Context
) {
2324 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2325 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2326 Printer
.printString("name", N
->getName());
2327 Printer
.printMetadata("file", N
->getRawFile());
2328 Printer
.printInt("line", N
->getLine());
2332 static void writeDIExpression(raw_ostream
&Out
, const DIExpression
*N
,
2333 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2334 const Module
*Context
) {
2335 Out
<< "!DIExpression(";
2338 for (const DIExpression::ExprOperand
&Op
: N
->expr_ops()) {
2339 auto OpStr
= dwarf::OperationEncodingString(Op
.getOp());
2340 assert(!OpStr
.empty() && "Expected valid opcode");
2343 if (Op
.getOp() == dwarf::DW_OP_LLVM_convert
) {
2344 Out
<< FS
<< Op
.getArg(0);
2345 Out
<< FS
<< dwarf::AttributeEncodingString(Op
.getArg(1));
2347 for (unsigned A
= 0, AE
= Op
.getNumArgs(); A
!= AE
; ++A
)
2348 Out
<< FS
<< Op
.getArg(A
);
2352 for (const auto &I
: N
->getElements())
2358 static void writeDIArgList(raw_ostream
&Out
, const DIArgList
*N
,
2359 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2360 const Module
*Context
, bool FromValue
= false) {
2362 "Unexpected DIArgList metadata outside of value argument");
2363 Out
<< "!DIArgList(";
2365 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2366 for (Metadata
*Arg
: N
->getArgs()) {
2368 WriteAsOperandInternal(Out
, Arg
, TypePrinter
, Machine
, Context
, true);
2373 static void writeDIGlobalVariableExpression(raw_ostream
&Out
,
2374 const DIGlobalVariableExpression
*N
,
2375 TypePrinting
*TypePrinter
,
2376 SlotTracker
*Machine
,
2377 const Module
*Context
) {
2378 Out
<< "!DIGlobalVariableExpression(";
2379 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2380 Printer
.printMetadata("var", N
->getVariable());
2381 Printer
.printMetadata("expr", N
->getExpression());
2385 static void writeDIObjCProperty(raw_ostream
&Out
, const DIObjCProperty
*N
,
2386 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2387 const Module
*Context
) {
2388 Out
<< "!DIObjCProperty(";
2389 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2390 Printer
.printString("name", N
->getName());
2391 Printer
.printMetadata("file", N
->getRawFile());
2392 Printer
.printInt("line", N
->getLine());
2393 Printer
.printString("setter", N
->getSetterName());
2394 Printer
.printString("getter", N
->getGetterName());
2395 Printer
.printInt("attributes", N
->getAttributes());
2396 Printer
.printMetadata("type", N
->getRawType());
2400 static void writeDIImportedEntity(raw_ostream
&Out
, const DIImportedEntity
*N
,
2401 TypePrinting
*TypePrinter
,
2402 SlotTracker
*Machine
, const Module
*Context
) {
2403 Out
<< "!DIImportedEntity(";
2404 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2405 Printer
.printTag(N
);
2406 Printer
.printString("name", N
->getName());
2407 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2408 Printer
.printMetadata("entity", N
->getRawEntity());
2409 Printer
.printMetadata("file", N
->getRawFile());
2410 Printer
.printInt("line", N
->getLine());
2414 static void WriteMDNodeBodyInternal(raw_ostream
&Out
, const MDNode
*Node
,
2415 TypePrinting
*TypePrinter
,
2416 SlotTracker
*Machine
,
2417 const Module
*Context
) {
2418 if (Node
->isDistinct())
2420 else if (Node
->isTemporary())
2421 Out
<< "<temporary!> "; // Handle broken code.
2423 switch (Node
->getMetadataID()) {
2425 llvm_unreachable("Expected uniquable MDNode");
2426 #define HANDLE_MDNODE_LEAF(CLASS) \
2427 case Metadata::CLASS##Kind: \
2428 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
2430 #include "llvm/IR/Metadata.def"
2434 // Full implementation of printing a Value as an operand with support for
2435 // TypePrinting, etc.
2436 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
2437 TypePrinting
*TypePrinter
,
2438 SlotTracker
*Machine
,
2439 const Module
*Context
) {
2441 PrintLLVMName(Out
, V
);
2445 const Constant
*CV
= dyn_cast
<Constant
>(V
);
2446 if (CV
&& !isa
<GlobalValue
>(CV
)) {
2447 assert(TypePrinter
&& "Constants require TypePrinting!");
2448 WriteConstantInternal(Out
, CV
, *TypePrinter
, Machine
, Context
);
2452 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
2454 if (IA
->hasSideEffects())
2455 Out
<< "sideeffect ";
2456 if (IA
->isAlignStack())
2457 Out
<< "alignstack ";
2458 // We don't emit the AD_ATT dialect as it's the assumed default.
2459 if (IA
->getDialect() == InlineAsm::AD_Intel
)
2460 Out
<< "inteldialect ";
2464 printEscapedString(IA
->getAsmString(), Out
);
2466 printEscapedString(IA
->getConstraintString(), Out
);
2471 if (auto *MD
= dyn_cast
<MetadataAsValue
>(V
)) {
2472 WriteAsOperandInternal(Out
, MD
->getMetadata(), TypePrinter
, Machine
,
2473 Context
, /* FromValue */ true);
2479 // If we have a SlotTracker, use it.
2481 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
2482 Slot
= Machine
->getGlobalSlot(GV
);
2485 Slot
= Machine
->getLocalSlot(V
);
2487 // If the local value didn't succeed, then we may be referring to a value
2488 // from a different function. Translate it, as this can happen when using
2489 // address of blocks.
2491 if ((Machine
= createSlotTracker(V
))) {
2492 Slot
= Machine
->getLocalSlot(V
);
2496 } else if ((Machine
= createSlotTracker(V
))) {
2497 // Otherwise, create one to get the # and then destroy it.
2498 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
2499 Slot
= Machine
->getGlobalSlot(GV
);
2502 Slot
= Machine
->getLocalSlot(V
);
2511 Out
<< Prefix
<< Slot
;
2516 static void WriteAsOperandInternal(raw_ostream
&Out
, const Metadata
*MD
,
2517 TypePrinting
*TypePrinter
,
2518 SlotTracker
*Machine
, const Module
*Context
,
2520 // Write DIExpressions and DIArgLists inline when used as a value. Improves
2521 // readability of debug info intrinsics.
2522 if (const DIExpression
*Expr
= dyn_cast
<DIExpression
>(MD
)) {
2523 writeDIExpression(Out
, Expr
, TypePrinter
, Machine
, Context
);
2526 if (const DIArgList
*ArgList
= dyn_cast
<DIArgList
>(MD
)) {
2527 writeDIArgList(Out
, ArgList
, TypePrinter
, Machine
, Context
, FromValue
);
2531 if (const MDNode
*N
= dyn_cast
<MDNode
>(MD
)) {
2532 std::unique_ptr
<SlotTracker
> MachineStorage
;
2534 MachineStorage
= std::make_unique
<SlotTracker
>(Context
);
2535 Machine
= MachineStorage
.get();
2537 int Slot
= Machine
->getMetadataSlot(N
);
2539 if (const DILocation
*Loc
= dyn_cast
<DILocation
>(N
)) {
2540 writeDILocation(Out
, Loc
, TypePrinter
, Machine
, Context
);
2543 // Give the pointer value instead of "badref", since this comes up all
2544 // the time when debugging.
2545 Out
<< "<" << N
<< ">";
2551 if (const MDString
*MDS
= dyn_cast
<MDString
>(MD
)) {
2553 printEscapedString(MDS
->getString(), Out
);
2558 auto *V
= cast
<ValueAsMetadata
>(MD
);
2559 assert(TypePrinter
&& "TypePrinter required for metadata values");
2560 assert((FromValue
|| !isa
<LocalAsMetadata
>(V
)) &&
2561 "Unexpected function-local metadata outside of value argument");
2563 TypePrinter
->print(V
->getValue()->getType(), Out
);
2565 WriteAsOperandInternal(Out
, V
->getValue(), TypePrinter
, Machine
, Context
);
2570 class AssemblyWriter
{
2571 formatted_raw_ostream
&Out
;
2572 const Module
*TheModule
= nullptr;
2573 const ModuleSummaryIndex
*TheIndex
= nullptr;
2574 std::unique_ptr
<SlotTracker
> SlotTrackerStorage
;
2575 SlotTracker
&Machine
;
2576 TypePrinting TypePrinter
;
2577 AssemblyAnnotationWriter
*AnnotationWriter
= nullptr;
2578 SetVector
<const Comdat
*> Comdats
;
2580 bool ShouldPreserveUseListOrder
;
2581 UseListOrderMap UseListOrders
;
2582 SmallVector
<StringRef
, 8> MDNames
;
2583 /// Synchronization scope names registered with LLVMContext.
2584 SmallVector
<StringRef
, 8> SSNs
;
2585 DenseMap
<const GlobalValueSummary
*, GlobalValue::GUID
> SummaryToGUIDMap
;
2588 /// Construct an AssemblyWriter with an external SlotTracker
2589 AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
, const Module
*M
,
2590 AssemblyAnnotationWriter
*AAW
, bool IsForDebug
,
2591 bool ShouldPreserveUseListOrder
= false);
2593 AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2594 const ModuleSummaryIndex
*Index
, bool IsForDebug
);
2596 void printMDNodeBody(const MDNode
*MD
);
2597 void printNamedMDNode(const NamedMDNode
*NMD
);
2599 void printModule(const Module
*M
);
2601 void writeOperand(const Value
*Op
, bool PrintType
);
2602 void writeParamOperand(const Value
*Operand
, AttributeSet Attrs
);
2603 void writeOperandBundles(const CallBase
*Call
);
2604 void writeSyncScope(const LLVMContext
&Context
,
2605 SyncScope::ID SSID
);
2606 void writeAtomic(const LLVMContext
&Context
,
2607 AtomicOrdering Ordering
,
2608 SyncScope::ID SSID
);
2609 void writeAtomicCmpXchg(const LLVMContext
&Context
,
2610 AtomicOrdering SuccessOrdering
,
2611 AtomicOrdering FailureOrdering
,
2612 SyncScope::ID SSID
);
2614 void writeAllMDNodes();
2615 void writeMDNode(unsigned Slot
, const MDNode
*Node
);
2616 void writeAttribute(const Attribute
&Attr
, bool InAttrGroup
= false);
2617 void writeAttributeSet(const AttributeSet
&AttrSet
, bool InAttrGroup
= false);
2618 void writeAllAttributeGroups();
2620 void printTypeIdentities();
2621 void printGlobal(const GlobalVariable
*GV
);
2622 void printIndirectSymbol(const GlobalIndirectSymbol
*GIS
);
2623 void printComdat(const Comdat
*C
);
2624 void printFunction(const Function
*F
);
2625 void printArgument(const Argument
*FA
, AttributeSet Attrs
);
2626 void printBasicBlock(const BasicBlock
*BB
);
2627 void printInstructionLine(const Instruction
&I
);
2628 void printInstruction(const Instruction
&I
);
2630 void printUseListOrder(const Value
*V
, const std::vector
<unsigned> &Shuffle
);
2631 void printUseLists(const Function
*F
);
2633 void printModuleSummaryIndex();
2634 void printSummaryInfo(unsigned Slot
, const ValueInfo
&VI
);
2635 void printSummary(const GlobalValueSummary
&Summary
);
2636 void printAliasSummary(const AliasSummary
*AS
);
2637 void printGlobalVarSummary(const GlobalVarSummary
*GS
);
2638 void printFunctionSummary(const FunctionSummary
*FS
);
2639 void printTypeIdSummary(const TypeIdSummary
&TIS
);
2640 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo
&TI
);
2641 void printTypeTestResolution(const TypeTestResolution
&TTRes
);
2642 void printArgs(const std::vector
<uint64_t> &Args
);
2643 void printWPDRes(const WholeProgramDevirtResolution
&WPDRes
);
2644 void printTypeIdInfo(const FunctionSummary::TypeIdInfo
&TIDInfo
);
2645 void printVFuncId(const FunctionSummary::VFuncId VFId
);
2647 printNonConstVCalls(const std::vector
<FunctionSummary::VFuncId
> &VCallList
,
2650 printConstVCalls(const std::vector
<FunctionSummary::ConstVCall
> &VCallList
,
2654 /// Print out metadata attachments.
2655 void printMetadataAttachments(
2656 const SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &MDs
,
2657 StringRef Separator
);
2659 // printInfoComment - Print a little comment after the instruction indicating
2660 // which slot it occupies.
2661 void printInfoComment(const Value
&V
);
2663 // printGCRelocateComment - print comment after call to the gc.relocate
2664 // intrinsic indicating base and derived pointer names.
2665 void printGCRelocateComment(const GCRelocateInst
&Relocate
);
2668 } // end anonymous namespace
2670 AssemblyWriter::AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2671 const Module
*M
, AssemblyAnnotationWriter
*AAW
,
2672 bool IsForDebug
, bool ShouldPreserveUseListOrder
)
2673 : Out(o
), TheModule(M
), Machine(Mac
), TypePrinter(M
), AnnotationWriter(AAW
),
2674 IsForDebug(IsForDebug
),
2675 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder
) {
2678 for (const GlobalObject
&GO
: TheModule
->global_objects())
2679 if (const Comdat
*C
= GO
.getComdat())
2683 AssemblyWriter::AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2684 const ModuleSummaryIndex
*Index
, bool IsForDebug
)
2685 : Out(o
), TheIndex(Index
), Machine(Mac
), TypePrinter(/*Module=*/nullptr),
2686 IsForDebug(IsForDebug
), ShouldPreserveUseListOrder(false) {}
2688 void AssemblyWriter::writeOperand(const Value
*Operand
, bool PrintType
) {
2690 Out
<< "<null operand!>";
2694 TypePrinter
.print(Operand
->getType(), Out
);
2697 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
2700 void AssemblyWriter::writeSyncScope(const LLVMContext
&Context
,
2701 SyncScope::ID SSID
) {
2703 case SyncScope::System
: {
2708 Context
.getSyncScopeNames(SSNs
);
2710 Out
<< " syncscope(\"";
2711 printEscapedString(SSNs
[SSID
], Out
);
2718 void AssemblyWriter::writeAtomic(const LLVMContext
&Context
,
2719 AtomicOrdering Ordering
,
2720 SyncScope::ID SSID
) {
2721 if (Ordering
== AtomicOrdering::NotAtomic
)
2724 writeSyncScope(Context
, SSID
);
2725 Out
<< " " << toIRString(Ordering
);
2728 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext
&Context
,
2729 AtomicOrdering SuccessOrdering
,
2730 AtomicOrdering FailureOrdering
,
2731 SyncScope::ID SSID
) {
2732 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
2733 FailureOrdering
!= AtomicOrdering::NotAtomic
);
2735 writeSyncScope(Context
, SSID
);
2736 Out
<< " " << toIRString(SuccessOrdering
);
2737 Out
<< " " << toIRString(FailureOrdering
);
2740 void AssemblyWriter::writeParamOperand(const Value
*Operand
,
2741 AttributeSet Attrs
) {
2743 Out
<< "<null operand!>";
2748 TypePrinter
.print(Operand
->getType(), Out
);
2749 // Print parameter attributes list
2750 if (Attrs
.hasAttributes()) {
2752 writeAttributeSet(Attrs
);
2755 // Print the operand
2756 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
2759 void AssemblyWriter::writeOperandBundles(const CallBase
*Call
) {
2760 if (!Call
->hasOperandBundles())
2765 bool FirstBundle
= true;
2766 for (unsigned i
= 0, e
= Call
->getNumOperandBundles(); i
!= e
; ++i
) {
2767 OperandBundleUse BU
= Call
->getOperandBundleAt(i
);
2771 FirstBundle
= false;
2774 printEscapedString(BU
.getTagName(), Out
);
2779 bool FirstInput
= true;
2780 for (const auto &Input
: BU
.Inputs
) {
2785 TypePrinter
.print(Input
->getType(), Out
);
2787 WriteAsOperandInternal(Out
, Input
, &TypePrinter
, &Machine
, TheModule
);
2796 void AssemblyWriter::printModule(const Module
*M
) {
2797 Machine
.initializeIfNeeded();
2799 if (ShouldPreserveUseListOrder
)
2800 UseListOrders
= predictUseListOrder(M
);
2802 if (!M
->getModuleIdentifier().empty() &&
2803 // Don't print the ID if it will start a new line (which would
2804 // require a comment char before it).
2805 M
->getModuleIdentifier().find('\n') == std::string::npos
)
2806 Out
<< "; ModuleID = '" << M
->getModuleIdentifier() << "'\n";
2808 if (!M
->getSourceFileName().empty()) {
2809 Out
<< "source_filename = \"";
2810 printEscapedString(M
->getSourceFileName(), Out
);
2814 const std::string
&DL
= M
->getDataLayoutStr();
2816 Out
<< "target datalayout = \"" << DL
<< "\"\n";
2817 if (!M
->getTargetTriple().empty())
2818 Out
<< "target triple = \"" << M
->getTargetTriple() << "\"\n";
2820 if (!M
->getModuleInlineAsm().empty()) {
2823 // Split the string into lines, to make it easier to read the .ll file.
2824 StringRef Asm
= M
->getModuleInlineAsm();
2827 std::tie(Front
, Asm
) = Asm
.split('\n');
2829 // We found a newline, print the portion of the asm string from the
2830 // last newline up to this newline.
2831 Out
<< "module asm \"";
2832 printEscapedString(Front
, Out
);
2834 } while (!Asm
.empty());
2837 printTypeIdentities();
2839 // Output all comdats.
2840 if (!Comdats
.empty())
2842 for (const Comdat
*C
: Comdats
) {
2844 if (C
!= Comdats
.back())
2848 // Output all globals.
2849 if (!M
->global_empty()) Out
<< '\n';
2850 for (const GlobalVariable
&GV
: M
->globals()) {
2851 printGlobal(&GV
); Out
<< '\n';
2854 // Output all aliases.
2855 if (!M
->alias_empty()) Out
<< "\n";
2856 for (const GlobalAlias
&GA
: M
->aliases())
2857 printIndirectSymbol(&GA
);
2859 // Output all ifuncs.
2860 if (!M
->ifunc_empty()) Out
<< "\n";
2861 for (const GlobalIFunc
&GI
: M
->ifuncs())
2862 printIndirectSymbol(&GI
);
2864 // Output all of the functions.
2865 for (const Function
&F
: *M
) {
2870 // Output global use-lists.
2871 printUseLists(nullptr);
2873 // Output all attribute groups.
2874 if (!Machine
.as_empty()) {
2876 writeAllAttributeGroups();
2879 // Output named metadata.
2880 if (!M
->named_metadata_empty()) Out
<< '\n';
2882 for (const NamedMDNode
&Node
: M
->named_metadata())
2883 printNamedMDNode(&Node
);
2886 if (!Machine
.mdn_empty()) {
2892 void AssemblyWriter::printModuleSummaryIndex() {
2894 int NumSlots
= Machine
.initializeIndexIfNeeded();
2898 // Print module path entries. To print in order, add paths to a vector
2899 // indexed by module slot.
2900 std::vector
<std::pair
<std::string
, ModuleHash
>> moduleVec
;
2901 std::string RegularLTOModuleName
=
2902 ModuleSummaryIndex::getRegularLTOModuleName();
2903 moduleVec
.resize(TheIndex
->modulePaths().size());
2904 for (auto &ModPath
: TheIndex
->modulePaths())
2905 moduleVec
[Machine
.getModulePathSlot(ModPath
.first())] = std::make_pair(
2906 // A module id of -1 is a special entry for a regular LTO module created
2907 // during the thin link.
2908 ModPath
.second
.first
== -1u ? RegularLTOModuleName
2909 : (std::string
)std::string(ModPath
.first()),
2910 ModPath
.second
.second
);
2913 for (auto &ModPair
: moduleVec
) {
2914 Out
<< "^" << i
++ << " = module: (";
2916 printEscapedString(ModPair
.first
, Out
);
2917 Out
<< "\", hash: (";
2919 for (auto Hash
: ModPair
.second
)
2924 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2925 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2926 for (auto &GlobalList
: *TheIndex
) {
2927 auto GUID
= GlobalList
.first
;
2928 for (auto &Summary
: GlobalList
.second
.SummaryList
)
2929 SummaryToGUIDMap
[Summary
.get()] = GUID
;
2932 // Print the global value summary entries.
2933 for (auto &GlobalList
: *TheIndex
) {
2934 auto GUID
= GlobalList
.first
;
2935 auto VI
= TheIndex
->getValueInfo(GlobalList
);
2936 printSummaryInfo(Machine
.getGUIDSlot(GUID
), VI
);
2939 // Print the TypeIdMap entries.
2940 for (const auto &TID
: TheIndex
->typeIds()) {
2941 Out
<< "^" << Machine
.getTypeIdSlot(TID
.second
.first
)
2942 << " = typeid: (name: \"" << TID
.second
.first
<< "\"";
2943 printTypeIdSummary(TID
.second
.second
);
2944 Out
<< ") ; guid = " << TID
.first
<< "\n";
2947 // Print the TypeIdCompatibleVtableMap entries.
2948 for (auto &TId
: TheIndex
->typeIdCompatibleVtableMap()) {
2949 auto GUID
= GlobalValue::getGUID(TId
.first
);
2950 Out
<< "^" << Machine
.getGUIDSlot(GUID
)
2951 << " = typeidCompatibleVTable: (name: \"" << TId
.first
<< "\"";
2952 printTypeIdCompatibleVtableSummary(TId
.second
);
2953 Out
<< ") ; guid = " << GUID
<< "\n";
2956 // Don't emit flags when it's not really needed (value is zero by default).
2957 if (TheIndex
->getFlags()) {
2958 Out
<< "^" << NumSlots
<< " = flags: " << TheIndex
->getFlags() << "\n";
2962 Out
<< "^" << NumSlots
<< " = blockcount: " << TheIndex
->getBlockCount()
2967 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K
) {
2969 case WholeProgramDevirtResolution::Indir
:
2971 case WholeProgramDevirtResolution::SingleImpl
:
2972 return "singleImpl";
2973 case WholeProgramDevirtResolution::BranchFunnel
:
2974 return "branchFunnel";
2976 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2979 static const char *getWholeProgDevirtResByArgKindName(
2980 WholeProgramDevirtResolution::ByArg::Kind K
) {
2982 case WholeProgramDevirtResolution::ByArg::Indir
:
2984 case WholeProgramDevirtResolution::ByArg::UniformRetVal
:
2985 return "uniformRetVal";
2986 case WholeProgramDevirtResolution::ByArg::UniqueRetVal
:
2987 return "uniqueRetVal";
2988 case WholeProgramDevirtResolution::ByArg::VirtualConstProp
:
2989 return "virtualConstProp";
2991 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2994 static const char *getTTResKindName(TypeTestResolution::Kind K
) {
2996 case TypeTestResolution::Unknown
:
2998 case TypeTestResolution::Unsat
:
3000 case TypeTestResolution::ByteArray
:
3002 case TypeTestResolution::Inline
:
3004 case TypeTestResolution::Single
:
3006 case TypeTestResolution::AllOnes
:
3009 llvm_unreachable("invalid TypeTestResolution kind");
3012 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution
&TTRes
) {
3013 Out
<< "typeTestRes: (kind: " << getTTResKindName(TTRes
.TheKind
)
3014 << ", sizeM1BitWidth: " << TTRes
.SizeM1BitWidth
;
3016 // The following fields are only used if the target does not support the use
3017 // of absolute symbols to store constants. Print only if non-zero.
3018 if (TTRes
.AlignLog2
)
3019 Out
<< ", alignLog2: " << TTRes
.AlignLog2
;
3021 Out
<< ", sizeM1: " << TTRes
.SizeM1
;
3023 // BitMask is uint8_t which causes it to print the corresponding char.
3024 Out
<< ", bitMask: " << (unsigned)TTRes
.BitMask
;
3025 if (TTRes
.InlineBits
)
3026 Out
<< ", inlineBits: " << TTRes
.InlineBits
;
3031 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary
&TIS
) {
3032 Out
<< ", summary: (";
3033 printTypeTestResolution(TIS
.TTRes
);
3034 if (!TIS
.WPDRes
.empty()) {
3035 Out
<< ", wpdResolutions: (";
3037 for (auto &WPDRes
: TIS
.WPDRes
) {
3039 Out
<< "(offset: " << WPDRes
.first
<< ", ";
3040 printWPDRes(WPDRes
.second
);
3048 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3049 const TypeIdCompatibleVtableInfo
&TI
) {
3050 Out
<< ", summary: (";
3052 for (auto &P
: TI
) {
3054 Out
<< "(offset: " << P
.AddressPointOffset
<< ", ";
3055 Out
<< "^" << Machine
.getGUIDSlot(P
.VTableVI
.getGUID());
3061 void AssemblyWriter::printArgs(const std::vector
<uint64_t> &Args
) {
3064 for (auto arg
: Args
) {
3071 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution
&WPDRes
) {
3072 Out
<< "wpdRes: (kind: ";
3073 Out
<< getWholeProgDevirtResKindName(WPDRes
.TheKind
);
3075 if (WPDRes
.TheKind
== WholeProgramDevirtResolution::SingleImpl
)
3076 Out
<< ", singleImplName: \"" << WPDRes
.SingleImplName
<< "\"";
3078 if (!WPDRes
.ResByArg
.empty()) {
3079 Out
<< ", resByArg: (";
3081 for (auto &ResByArg
: WPDRes
.ResByArg
) {
3083 printArgs(ResByArg
.first
);
3084 Out
<< ", byArg: (kind: ";
3085 Out
<< getWholeProgDevirtResByArgKindName(ResByArg
.second
.TheKind
);
3086 if (ResByArg
.second
.TheKind
==
3087 WholeProgramDevirtResolution::ByArg::UniformRetVal
||
3088 ResByArg
.second
.TheKind
==
3089 WholeProgramDevirtResolution::ByArg::UniqueRetVal
)
3090 Out
<< ", info: " << ResByArg
.second
.Info
;
3092 // The following fields are only used if the target does not support the
3093 // use of absolute symbols to store constants. Print only if non-zero.
3094 if (ResByArg
.second
.Byte
|| ResByArg
.second
.Bit
)
3095 Out
<< ", byte: " << ResByArg
.second
.Byte
3096 << ", bit: " << ResByArg
.second
.Bit
;
3105 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK
) {
3107 case GlobalValueSummary::AliasKind
:
3109 case GlobalValueSummary::FunctionKind
:
3111 case GlobalValueSummary::GlobalVarKind
:
3114 llvm_unreachable("invalid summary kind");
3117 void AssemblyWriter::printAliasSummary(const AliasSummary
*AS
) {
3118 Out
<< ", aliasee: ";
3119 // The indexes emitted for distributed backends may not include the
3120 // aliasee summary (only if it is being imported directly). Handle
3121 // that case by just emitting "null" as the aliasee.
3122 if (AS
->hasAliasee())
3123 Out
<< "^" << Machine
.getGUIDSlot(SummaryToGUIDMap
[&AS
->getAliasee()]);
3128 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary
*GS
) {
3129 auto VTableFuncs
= GS
->vTableFuncs();
3130 Out
<< ", varFlags: (readonly: " << GS
->VarFlags
.MaybeReadOnly
<< ", "
3131 << "writeonly: " << GS
->VarFlags
.MaybeWriteOnly
<< ", "
3132 << "constant: " << GS
->VarFlags
.Constant
;
3133 if (!VTableFuncs
.empty())
3135 << "vcall_visibility: " << GS
->VarFlags
.VCallVisibility
;
3138 if (!VTableFuncs
.empty()) {
3139 Out
<< ", vTableFuncs: (";
3141 for (auto &P
: VTableFuncs
) {
3143 Out
<< "(virtFunc: ^" << Machine
.getGUIDSlot(P
.FuncVI
.getGUID())
3144 << ", offset: " << P
.VTableOffset
;
3151 static std::string
getLinkageName(GlobalValue::LinkageTypes LT
) {
3153 case GlobalValue::ExternalLinkage
:
3155 case GlobalValue::PrivateLinkage
:
3157 case GlobalValue::InternalLinkage
:
3159 case GlobalValue::LinkOnceAnyLinkage
:
3161 case GlobalValue::LinkOnceODRLinkage
:
3162 return "linkonce_odr";
3163 case GlobalValue::WeakAnyLinkage
:
3165 case GlobalValue::WeakODRLinkage
:
3167 case GlobalValue::CommonLinkage
:
3169 case GlobalValue::AppendingLinkage
:
3171 case GlobalValue::ExternalWeakLinkage
:
3172 return "extern_weak";
3173 case GlobalValue::AvailableExternallyLinkage
:
3174 return "available_externally";
3176 llvm_unreachable("invalid linkage");
3179 // When printing the linkage types in IR where the ExternalLinkage is
3180 // not printed, and other linkage types are expected to be printed with
3181 // a space after the name.
3182 static std::string
getLinkageNameWithSpace(GlobalValue::LinkageTypes LT
) {
3183 if (LT
== GlobalValue::ExternalLinkage
)
3185 return getLinkageName(LT
) + " ";
3188 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis
) {
3190 case GlobalValue::DefaultVisibility
:
3192 case GlobalValue::HiddenVisibility
:
3194 case GlobalValue::ProtectedVisibility
:
3197 llvm_unreachable("invalid visibility");
3200 void AssemblyWriter::printFunctionSummary(const FunctionSummary
*FS
) {
3201 Out
<< ", insts: " << FS
->instCount();
3203 FunctionSummary::FFlags FFlags
= FS
->fflags();
3204 if (FFlags
.ReadNone
| FFlags
.ReadOnly
| FFlags
.NoRecurse
|
3205 FFlags
.ReturnDoesNotAlias
| FFlags
.NoInline
| FFlags
.AlwaysInline
) {
3206 Out
<< ", funcFlags: (";
3207 Out
<< "readNone: " << FFlags
.ReadNone
;
3208 Out
<< ", readOnly: " << FFlags
.ReadOnly
;
3209 Out
<< ", noRecurse: " << FFlags
.NoRecurse
;
3210 Out
<< ", returnDoesNotAlias: " << FFlags
.ReturnDoesNotAlias
;
3211 Out
<< ", noInline: " << FFlags
.NoInline
;
3212 Out
<< ", alwaysInline: " << FFlags
.AlwaysInline
;
3215 if (!FS
->calls().empty()) {
3216 Out
<< ", calls: (";
3218 for (auto &Call
: FS
->calls()) {
3220 Out
<< "(callee: ^" << Machine
.getGUIDSlot(Call
.first
.getGUID());
3221 if (Call
.second
.getHotness() != CalleeInfo::HotnessType::Unknown
)
3222 Out
<< ", hotness: " << getHotnessName(Call
.second
.getHotness());
3223 else if (Call
.second
.RelBlockFreq
)
3224 Out
<< ", relbf: " << Call
.second
.RelBlockFreq
;
3230 if (const auto *TIdInfo
= FS
->getTypeIdInfo())
3231 printTypeIdInfo(*TIdInfo
);
3233 auto PrintRange
= [&](const ConstantRange
&Range
) {
3234 Out
<< "[" << Range
.getSignedMin() << ", " << Range
.getSignedMax() << "]";
3237 if (!FS
->paramAccesses().empty()) {
3238 Out
<< ", params: (";
3240 for (auto &PS
: FS
->paramAccesses()) {
3242 Out
<< "(param: " << PS
.ParamNo
;
3243 Out
<< ", offset: ";
3245 if (!PS
.Calls
.empty()) {
3246 Out
<< ", calls: (";
3248 for (auto &Call
: PS
.Calls
) {
3250 Out
<< "(callee: ^" << Machine
.getGUIDSlot(Call
.Callee
.getGUID());
3251 Out
<< ", param: " << Call
.ParamNo
;
3252 Out
<< ", offset: ";
3253 PrintRange(Call
.Offsets
);
3264 void AssemblyWriter::printTypeIdInfo(
3265 const FunctionSummary::TypeIdInfo
&TIDInfo
) {
3266 Out
<< ", typeIdInfo: (";
3267 FieldSeparator TIDFS
;
3268 if (!TIDInfo
.TypeTests
.empty()) {
3270 Out
<< "typeTests: (";
3272 for (auto &GUID
: TIDInfo
.TypeTests
) {
3273 auto TidIter
= TheIndex
->typeIds().equal_range(GUID
);
3274 if (TidIter
.first
== TidIter
.second
) {
3279 // Print all type id that correspond to this GUID.
3280 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
3282 auto Slot
= Machine
.getTypeIdSlot(It
->second
.first
);
3289 if (!TIDInfo
.TypeTestAssumeVCalls
.empty()) {
3291 printNonConstVCalls(TIDInfo
.TypeTestAssumeVCalls
, "typeTestAssumeVCalls");
3293 if (!TIDInfo
.TypeCheckedLoadVCalls
.empty()) {
3295 printNonConstVCalls(TIDInfo
.TypeCheckedLoadVCalls
, "typeCheckedLoadVCalls");
3297 if (!TIDInfo
.TypeTestAssumeConstVCalls
.empty()) {
3299 printConstVCalls(TIDInfo
.TypeTestAssumeConstVCalls
,
3300 "typeTestAssumeConstVCalls");
3302 if (!TIDInfo
.TypeCheckedLoadConstVCalls
.empty()) {
3304 printConstVCalls(TIDInfo
.TypeCheckedLoadConstVCalls
,
3305 "typeCheckedLoadConstVCalls");
3310 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId
) {
3311 auto TidIter
= TheIndex
->typeIds().equal_range(VFId
.GUID
);
3312 if (TidIter
.first
== TidIter
.second
) {
3313 Out
<< "vFuncId: (";
3314 Out
<< "guid: " << VFId
.GUID
;
3315 Out
<< ", offset: " << VFId
.Offset
;
3319 // Print all type id that correspond to this GUID.
3321 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
3323 Out
<< "vFuncId: (";
3324 auto Slot
= Machine
.getTypeIdSlot(It
->second
.first
);
3327 Out
<< ", offset: " << VFId
.Offset
;
3332 void AssemblyWriter::printNonConstVCalls(
3333 const std::vector
<FunctionSummary::VFuncId
> &VCallList
, const char *Tag
) {
3334 Out
<< Tag
<< ": (";
3336 for (auto &VFuncId
: VCallList
) {
3338 printVFuncId(VFuncId
);
3343 void AssemblyWriter::printConstVCalls(
3344 const std::vector
<FunctionSummary::ConstVCall
> &VCallList
,
3346 Out
<< Tag
<< ": (";
3348 for (auto &ConstVCall
: VCallList
) {
3351 printVFuncId(ConstVCall
.VFunc
);
3352 if (!ConstVCall
.Args
.empty()) {
3354 printArgs(ConstVCall
.Args
);
3361 void AssemblyWriter::printSummary(const GlobalValueSummary
&Summary
) {
3362 GlobalValueSummary::GVFlags GVFlags
= Summary
.flags();
3363 GlobalValue::LinkageTypes LT
= (GlobalValue::LinkageTypes
)GVFlags
.Linkage
;
3364 Out
<< getSummaryKindName(Summary
.getSummaryKind()) << ": ";
3365 Out
<< "(module: ^" << Machine
.getModulePathSlot(Summary
.modulePath())
3367 Out
<< "linkage: " << getLinkageName(LT
);
3368 Out
<< ", visibility: "
3369 << getVisibilityName((GlobalValue::VisibilityTypes
)GVFlags
.Visibility
);
3370 Out
<< ", notEligibleToImport: " << GVFlags
.NotEligibleToImport
;
3371 Out
<< ", live: " << GVFlags
.Live
;
3372 Out
<< ", dsoLocal: " << GVFlags
.DSOLocal
;
3373 Out
<< ", canAutoHide: " << GVFlags
.CanAutoHide
;
3376 if (Summary
.getSummaryKind() == GlobalValueSummary::AliasKind
)
3377 printAliasSummary(cast
<AliasSummary
>(&Summary
));
3378 else if (Summary
.getSummaryKind() == GlobalValueSummary::FunctionKind
)
3379 printFunctionSummary(cast
<FunctionSummary
>(&Summary
));
3381 printGlobalVarSummary(cast
<GlobalVarSummary
>(&Summary
));
3383 auto RefList
= Summary
.refs();
3384 if (!RefList
.empty()) {
3387 for (auto &Ref
: RefList
) {
3389 if (Ref
.isReadOnly())
3391 else if (Ref
.isWriteOnly())
3392 Out
<< "writeonly ";
3393 Out
<< "^" << Machine
.getGUIDSlot(Ref
.getGUID());
3401 void AssemblyWriter::printSummaryInfo(unsigned Slot
, const ValueInfo
&VI
) {
3402 Out
<< "^" << Slot
<< " = gv: (";
3403 if (!VI
.name().empty())
3404 Out
<< "name: \"" << VI
.name() << "\"";
3406 Out
<< "guid: " << VI
.getGUID();
3407 if (!VI
.getSummaryList().empty()) {
3408 Out
<< ", summaries: (";
3410 for (auto &Summary
: VI
.getSummaryList()) {
3412 printSummary(*Summary
);
3417 if (!VI
.name().empty())
3418 Out
<< " ; guid = " << VI
.getGUID();
3422 static void printMetadataIdentifier(StringRef Name
,
3423 formatted_raw_ostream
&Out
) {
3425 Out
<< "<empty name> ";
3427 if (isalpha(static_cast<unsigned char>(Name
[0])) || Name
[0] == '-' ||
3428 Name
[0] == '$' || Name
[0] == '.' || Name
[0] == '_')
3431 Out
<< '\\' << hexdigit(Name
[0] >> 4) << hexdigit(Name
[0] & 0x0F);
3432 for (unsigned i
= 1, e
= Name
.size(); i
!= e
; ++i
) {
3433 unsigned char C
= Name
[i
];
3434 if (isalnum(static_cast<unsigned char>(C
)) || C
== '-' || C
== '$' ||
3435 C
== '.' || C
== '_')
3438 Out
<< '\\' << hexdigit(C
>> 4) << hexdigit(C
& 0x0F);
3443 void AssemblyWriter::printNamedMDNode(const NamedMDNode
*NMD
) {
3445 printMetadataIdentifier(NMD
->getName(), Out
);
3447 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
3451 // Write DIExpressions inline.
3452 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3453 MDNode
*Op
= NMD
->getOperand(i
);
3454 assert(!isa
<DIArgList
>(Op
) &&
3455 "DIArgLists should not appear in NamedMDNodes");
3456 if (auto *Expr
= dyn_cast
<DIExpression
>(Op
)) {
3457 writeDIExpression(Out
, Expr
, nullptr, nullptr, nullptr);
3461 int Slot
= Machine
.getMetadataSlot(Op
);
3470 static void PrintVisibility(GlobalValue::VisibilityTypes Vis
,
3471 formatted_raw_ostream
&Out
) {
3473 case GlobalValue::DefaultVisibility
: break;
3474 case GlobalValue::HiddenVisibility
: Out
<< "hidden "; break;
3475 case GlobalValue::ProtectedVisibility
: Out
<< "protected "; break;
3479 static void PrintDSOLocation(const GlobalValue
&GV
,
3480 formatted_raw_ostream
&Out
) {
3481 if (GV
.isDSOLocal() && !GV
.isImplicitDSOLocal())
3482 Out
<< "dso_local ";
3485 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT
,
3486 formatted_raw_ostream
&Out
) {
3488 case GlobalValue::DefaultStorageClass
: break;
3489 case GlobalValue::DLLImportStorageClass
: Out
<< "dllimport "; break;
3490 case GlobalValue::DLLExportStorageClass
: Out
<< "dllexport "; break;
3494 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM
,
3495 formatted_raw_ostream
&Out
) {
3497 case GlobalVariable::NotThreadLocal
:
3499 case GlobalVariable::GeneralDynamicTLSModel
:
3500 Out
<< "thread_local ";
3502 case GlobalVariable::LocalDynamicTLSModel
:
3503 Out
<< "thread_local(localdynamic) ";
3505 case GlobalVariable::InitialExecTLSModel
:
3506 Out
<< "thread_local(initialexec) ";
3508 case GlobalVariable::LocalExecTLSModel
:
3509 Out
<< "thread_local(localexec) ";
3514 static StringRef
getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA
) {
3516 case GlobalVariable::UnnamedAddr::None
:
3518 case GlobalVariable::UnnamedAddr::Local
:
3519 return "local_unnamed_addr";
3520 case GlobalVariable::UnnamedAddr::Global
:
3521 return "unnamed_addr";
3523 llvm_unreachable("Unknown UnnamedAddr");
3526 static void maybePrintComdat(formatted_raw_ostream
&Out
,
3527 const GlobalObject
&GO
) {
3528 const Comdat
*C
= GO
.getComdat();
3532 if (isa
<GlobalVariable
>(GO
))
3536 if (GO
.getName() == C
->getName())
3540 PrintLLVMName(Out
, C
->getName(), ComdatPrefix
);
3544 void AssemblyWriter::printGlobal(const GlobalVariable
*GV
) {
3545 if (GV
->isMaterializable())
3546 Out
<< "; Materializable\n";
3548 WriteAsOperandInternal(Out
, GV
, &TypePrinter
, &Machine
, GV
->getParent());
3551 if (!GV
->hasInitializer() && GV
->hasExternalLinkage())
3554 Out
<< getLinkageNameWithSpace(GV
->getLinkage());
3555 PrintDSOLocation(*GV
, Out
);
3556 PrintVisibility(GV
->getVisibility(), Out
);
3557 PrintDLLStorageClass(GV
->getDLLStorageClass(), Out
);
3558 PrintThreadLocalModel(GV
->getThreadLocalMode(), Out
);
3559 StringRef UA
= getUnnamedAddrEncoding(GV
->getUnnamedAddr());
3563 if (unsigned AddressSpace
= GV
->getType()->getAddressSpace())
3564 Out
<< "addrspace(" << AddressSpace
<< ") ";
3565 if (GV
->isExternallyInitialized()) Out
<< "externally_initialized ";
3566 Out
<< (GV
->isConstant() ? "constant " : "global ");
3567 TypePrinter
.print(GV
->getValueType(), Out
);
3569 if (GV
->hasInitializer()) {
3571 writeOperand(GV
->getInitializer(), false);
3574 if (GV
->hasSection()) {
3575 Out
<< ", section \"";
3576 printEscapedString(GV
->getSection(), Out
);
3579 if (GV
->hasPartition()) {
3580 Out
<< ", partition \"";
3581 printEscapedString(GV
->getPartition(), Out
);
3585 maybePrintComdat(Out
, *GV
);
3586 if (GV
->getAlignment())
3587 Out
<< ", align " << GV
->getAlignment();
3589 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3590 GV
->getAllMetadata(MDs
);
3591 printMetadataAttachments(MDs
, ", ");
3593 auto Attrs
= GV
->getAttributes();
3594 if (Attrs
.hasAttributes())
3595 Out
<< " #" << Machine
.getAttributeGroupSlot(Attrs
);
3597 printInfoComment(*GV
);
3600 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol
*GIS
) {
3601 if (GIS
->isMaterializable())
3602 Out
<< "; Materializable\n";
3604 WriteAsOperandInternal(Out
, GIS
, &TypePrinter
, &Machine
, GIS
->getParent());
3607 Out
<< getLinkageNameWithSpace(GIS
->getLinkage());
3608 PrintDSOLocation(*GIS
, Out
);
3609 PrintVisibility(GIS
->getVisibility(), Out
);
3610 PrintDLLStorageClass(GIS
->getDLLStorageClass(), Out
);
3611 PrintThreadLocalModel(GIS
->getThreadLocalMode(), Out
);
3612 StringRef UA
= getUnnamedAddrEncoding(GIS
->getUnnamedAddr());
3616 if (isa
<GlobalAlias
>(GIS
))
3618 else if (isa
<GlobalIFunc
>(GIS
))
3621 llvm_unreachable("Not an alias or ifunc!");
3623 TypePrinter
.print(GIS
->getValueType(), Out
);
3627 const Constant
*IS
= GIS
->getIndirectSymbol();
3630 TypePrinter
.print(GIS
->getType(), Out
);
3631 Out
<< " <<NULL ALIASEE>>";
3633 writeOperand(IS
, !isa
<ConstantExpr
>(IS
));
3636 if (GIS
->hasPartition()) {
3637 Out
<< ", partition \"";
3638 printEscapedString(GIS
->getPartition(), Out
);
3642 printInfoComment(*GIS
);
3646 void AssemblyWriter::printComdat(const Comdat
*C
) {
3650 void AssemblyWriter::printTypeIdentities() {
3651 if (TypePrinter
.empty())
3656 // Emit all numbered types.
3657 auto &NumberedTypes
= TypePrinter
.getNumberedTypes();
3658 for (unsigned I
= 0, E
= NumberedTypes
.size(); I
!= E
; ++I
) {
3659 Out
<< '%' << I
<< " = type ";
3661 // Make sure we print out at least one level of the type structure, so
3662 // that we do not get %2 = type %2
3663 TypePrinter
.printStructBody(NumberedTypes
[I
], Out
);
3667 auto &NamedTypes
= TypePrinter
.getNamedTypes();
3668 for (unsigned I
= 0, E
= NamedTypes
.size(); I
!= E
; ++I
) {
3669 PrintLLVMName(Out
, NamedTypes
[I
]->getName(), LocalPrefix
);
3672 // Make sure we print out at least one level of the type structure, so
3673 // that we do not get %FILE = type %FILE
3674 TypePrinter
.printStructBody(NamedTypes
[I
], Out
);
3679 /// printFunction - Print all aspects of a function.
3680 void AssemblyWriter::printFunction(const Function
*F
) {
3681 if (AnnotationWriter
) AnnotationWriter
->emitFunctionAnnot(F
, Out
);
3683 if (F
->isMaterializable())
3684 Out
<< "; Materializable\n";
3686 const AttributeList
&Attrs
= F
->getAttributes();
3687 if (Attrs
.hasFnAttrs()) {
3688 AttributeSet AS
= Attrs
.getFnAttrs();
3689 std::string AttrStr
;
3691 for (const Attribute
&Attr
: AS
) {
3692 if (!Attr
.isStringAttribute()) {
3693 if (!AttrStr
.empty()) AttrStr
+= ' ';
3694 AttrStr
+= Attr
.getAsString();
3698 if (!AttrStr
.empty())
3699 Out
<< "; Function Attrs: " << AttrStr
<< '\n';
3702 Machine
.incorporateFunction(F
);
3704 if (F
->isDeclaration()) {
3706 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3707 F
->getAllMetadata(MDs
);
3708 printMetadataAttachments(MDs
, " ");
3713 Out
<< getLinkageNameWithSpace(F
->getLinkage());
3714 PrintDSOLocation(*F
, Out
);
3715 PrintVisibility(F
->getVisibility(), Out
);
3716 PrintDLLStorageClass(F
->getDLLStorageClass(), Out
);
3718 // Print the calling convention.
3719 if (F
->getCallingConv() != CallingConv::C
) {
3720 PrintCallingConv(F
->getCallingConv(), Out
);
3724 FunctionType
*FT
= F
->getFunctionType();
3725 if (Attrs
.hasRetAttrs())
3726 Out
<< Attrs
.getAsString(AttributeList::ReturnIndex
) << ' ';
3727 TypePrinter
.print(F
->getReturnType(), Out
);
3729 WriteAsOperandInternal(Out
, F
, &TypePrinter
, &Machine
, F
->getParent());
3732 // Loop over the arguments, printing them...
3733 if (F
->isDeclaration() && !IsForDebug
) {
3734 // We're only interested in the type here - don't print argument names.
3735 for (unsigned I
= 0, E
= FT
->getNumParams(); I
!= E
; ++I
) {
3736 // Insert commas as we go... the first arg doesn't get a comma
3740 TypePrinter
.print(FT
->getParamType(I
), Out
);
3742 AttributeSet ArgAttrs
= Attrs
.getParamAttrs(I
);
3743 if (ArgAttrs
.hasAttributes()) {
3745 writeAttributeSet(ArgAttrs
);
3749 // The arguments are meaningful here, print them in detail.
3750 for (const Argument
&Arg
: F
->args()) {
3751 // Insert commas as we go... the first arg doesn't get a comma
3752 if (Arg
.getArgNo() != 0)
3754 printArgument(&Arg
, Attrs
.getParamAttrs(Arg
.getArgNo()));
3758 // Finish printing arguments...
3759 if (FT
->isVarArg()) {
3760 if (FT
->getNumParams()) Out
<< ", ";
3761 Out
<< "..."; // Output varargs portion of signature!
3764 StringRef UA
= getUnnamedAddrEncoding(F
->getUnnamedAddr());
3767 // We print the function address space if it is non-zero or if we are writing
3768 // a module with a non-zero program address space or if there is no valid
3769 // Module* so that the file can be parsed without the datalayout string.
3770 const Module
*Mod
= F
->getParent();
3771 if (F
->getAddressSpace() != 0 || !Mod
||
3772 Mod
->getDataLayout().getProgramAddressSpace() != 0)
3773 Out
<< " addrspace(" << F
->getAddressSpace() << ")";
3774 if (Attrs
.hasFnAttrs())
3775 Out
<< " #" << Machine
.getAttributeGroupSlot(Attrs
.getFnAttrs());
3776 if (F
->hasSection()) {
3777 Out
<< " section \"";
3778 printEscapedString(F
->getSection(), Out
);
3781 if (F
->hasPartition()) {
3782 Out
<< " partition \"";
3783 printEscapedString(F
->getPartition(), Out
);
3786 maybePrintComdat(Out
, *F
);
3787 if (F
->getAlignment())
3788 Out
<< " align " << F
->getAlignment();
3790 Out
<< " gc \"" << F
->getGC() << '"';
3791 if (F
->hasPrefixData()) {
3793 writeOperand(F
->getPrefixData(), true);
3795 if (F
->hasPrologueData()) {
3796 Out
<< " prologue ";
3797 writeOperand(F
->getPrologueData(), true);
3799 if (F
->hasPersonalityFn()) {
3800 Out
<< " personality ";
3801 writeOperand(F
->getPersonalityFn(), /*PrintType=*/true);
3804 if (F
->isDeclaration()) {
3807 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3808 F
->getAllMetadata(MDs
);
3809 printMetadataAttachments(MDs
, " ");
3812 // Output all of the function's basic blocks.
3813 for (const BasicBlock
&BB
: *F
)
3814 printBasicBlock(&BB
);
3816 // Output the function's use-lists.
3822 Machine
.purgeFunction();
3825 /// printArgument - This member is called for every argument that is passed into
3826 /// the function. Simply print it out
3827 void AssemblyWriter::printArgument(const Argument
*Arg
, AttributeSet Attrs
) {
3829 TypePrinter
.print(Arg
->getType(), Out
);
3831 // Output parameter attributes list
3832 if (Attrs
.hasAttributes()) {
3834 writeAttributeSet(Attrs
);
3837 // Output name, if available...
3838 if (Arg
->hasName()) {
3840 PrintLLVMName(Out
, Arg
);
3842 int Slot
= Machine
.getLocalSlot(Arg
);
3843 assert(Slot
!= -1 && "expect argument in function here");
3844 Out
<< " %" << Slot
;
3848 /// printBasicBlock - This member is called for each basic block in a method.
3849 void AssemblyWriter::printBasicBlock(const BasicBlock
*BB
) {
3850 bool IsEntryBlock
= BB
->getParent() && BB
->isEntryBlock();
3851 if (BB
->hasName()) { // Print out the label if it exists...
3853 PrintLLVMName(Out
, BB
->getName(), LabelPrefix
);
3855 } else if (!IsEntryBlock
) {
3857 int Slot
= Machine
.getLocalSlot(BB
);
3864 if (!IsEntryBlock
) {
3865 // Output predecessors for the block.
3866 Out
.PadToColumn(50);
3868 const_pred_iterator PI
= pred_begin(BB
), PE
= pred_end(BB
);
3871 Out
<< " No predecessors!";
3874 writeOperand(*PI
, false);
3875 for (++PI
; PI
!= PE
; ++PI
) {
3877 writeOperand(*PI
, false);
3884 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockStartAnnot(BB
, Out
);
3886 // Output all of the instructions in the basic block...
3887 for (const Instruction
&I
: *BB
) {
3888 printInstructionLine(I
);
3891 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockEndAnnot(BB
, Out
);
3894 /// printInstructionLine - Print an instruction and a newline character.
3895 void AssemblyWriter::printInstructionLine(const Instruction
&I
) {
3896 printInstruction(I
);
3900 /// printGCRelocateComment - print comment after call to the gc.relocate
3901 /// intrinsic indicating base and derived pointer names.
3902 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst
&Relocate
) {
3904 writeOperand(Relocate
.getBasePtr(), false);
3906 writeOperand(Relocate
.getDerivedPtr(), false);
3910 /// printInfoComment - Print a little comment after the instruction indicating
3911 /// which slot it occupies.
3912 void AssemblyWriter::printInfoComment(const Value
&V
) {
3913 if (const auto *Relocate
= dyn_cast
<GCRelocateInst
>(&V
))
3914 printGCRelocateComment(*Relocate
);
3916 if (AnnotationWriter
)
3917 AnnotationWriter
->printInfoComment(V
, Out
);
3920 static void maybePrintCallAddrSpace(const Value
*Operand
, const Instruction
*I
,
3922 // We print the address space of the call if it is non-zero.
3923 unsigned CallAddrSpace
= Operand
->getType()->getPointerAddressSpace();
3924 bool PrintAddrSpace
= CallAddrSpace
!= 0;
3925 if (!PrintAddrSpace
) {
3926 const Module
*Mod
= getModuleFromVal(I
);
3927 // We also print it if it is zero but not equal to the program address space
3928 // or if we can't find a valid Module* to make it possible to parse
3929 // the resulting file even without a datalayout string.
3930 if (!Mod
|| Mod
->getDataLayout().getProgramAddressSpace() != 0)
3931 PrintAddrSpace
= true;
3934 Out
<< " addrspace(" << CallAddrSpace
<< ")";
3937 // This member is called for each Instruction in a function..
3938 void AssemblyWriter::printInstruction(const Instruction
&I
) {
3939 if (AnnotationWriter
) AnnotationWriter
->emitInstructionAnnot(&I
, Out
);
3941 // Print out indentation for an instruction.
3944 // Print out name if it exists...
3946 PrintLLVMName(Out
, &I
);
3948 } else if (!I
.getType()->isVoidTy()) {
3949 // Print out the def slot taken.
3950 int SlotNum
= Machine
.getLocalSlot(&I
);
3952 Out
<< "<badref> = ";
3954 Out
<< '%' << SlotNum
<< " = ";
3957 if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
3958 if (CI
->isMustTailCall())
3960 else if (CI
->isTailCall())
3962 else if (CI
->isNoTailCall())
3966 // Print out the opcode...
3967 Out
<< I
.getOpcodeName();
3969 // If this is an atomic load or store, print out the atomic marker.
3970 if ((isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).isAtomic()) ||
3971 (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).isAtomic()))
3974 if (isa
<AtomicCmpXchgInst
>(I
) && cast
<AtomicCmpXchgInst
>(I
).isWeak())
3977 // If this is a volatile operation, print out the volatile marker.
3978 if ((isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).isVolatile()) ||
3979 (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).isVolatile()) ||
3980 (isa
<AtomicCmpXchgInst
>(I
) && cast
<AtomicCmpXchgInst
>(I
).isVolatile()) ||
3981 (isa
<AtomicRMWInst
>(I
) && cast
<AtomicRMWInst
>(I
).isVolatile()))
3984 // Print out optimization information.
3985 WriteOptimizationInfo(Out
, &I
);
3987 // Print out the compare instruction predicates
3988 if (const CmpInst
*CI
= dyn_cast
<CmpInst
>(&I
))
3989 Out
<< ' ' << CmpInst::getPredicateName(CI
->getPredicate());
3991 // Print out the atomicrmw operation
3992 if (const AtomicRMWInst
*RMWI
= dyn_cast
<AtomicRMWInst
>(&I
))
3993 Out
<< ' ' << AtomicRMWInst::getOperationName(RMWI
->getOperation());
3995 // Print out the type of the operands...
3996 const Value
*Operand
= I
.getNumOperands() ? I
.getOperand(0) : nullptr;
3998 // Special case conditional branches to swizzle the condition out to the front
3999 if (isa
<BranchInst
>(I
) && cast
<BranchInst
>(I
).isConditional()) {
4000 const BranchInst
&BI(cast
<BranchInst
>(I
));
4002 writeOperand(BI
.getCondition(), true);
4004 writeOperand(BI
.getSuccessor(0), true);
4006 writeOperand(BI
.getSuccessor(1), true);
4008 } else if (isa
<SwitchInst
>(I
)) {
4009 const SwitchInst
& SI(cast
<SwitchInst
>(I
));
4010 // Special case switch instruction to get formatting nice and correct.
4012 writeOperand(SI
.getCondition(), true);
4014 writeOperand(SI
.getDefaultDest(), true);
4016 for (auto Case
: SI
.cases()) {
4018 writeOperand(Case
.getCaseValue(), true);
4020 writeOperand(Case
.getCaseSuccessor(), true);
4023 } else if (isa
<IndirectBrInst
>(I
)) {
4024 // Special case indirectbr instruction to get formatting nice and correct.
4026 writeOperand(Operand
, true);
4029 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
) {
4032 writeOperand(I
.getOperand(i
), true);
4035 } else if (const PHINode
*PN
= dyn_cast
<PHINode
>(&I
)) {
4037 TypePrinter
.print(I
.getType(), Out
);
4040 for (unsigned op
= 0, Eop
= PN
->getNumIncomingValues(); op
< Eop
; ++op
) {
4041 if (op
) Out
<< ", ";
4043 writeOperand(PN
->getIncomingValue(op
), false); Out
<< ", ";
4044 writeOperand(PN
->getIncomingBlock(op
), false); Out
<< " ]";
4046 } else if (const ExtractValueInst
*EVI
= dyn_cast
<ExtractValueInst
>(&I
)) {
4048 writeOperand(I
.getOperand(0), true);
4049 for (unsigned i
: EVI
->indices())
4051 } else if (const InsertValueInst
*IVI
= dyn_cast
<InsertValueInst
>(&I
)) {
4053 writeOperand(I
.getOperand(0), true); Out
<< ", ";
4054 writeOperand(I
.getOperand(1), true);
4055 for (unsigned i
: IVI
->indices())
4057 } else if (const LandingPadInst
*LPI
= dyn_cast
<LandingPadInst
>(&I
)) {
4059 TypePrinter
.print(I
.getType(), Out
);
4060 if (LPI
->isCleanup() || LPI
->getNumClauses() != 0)
4063 if (LPI
->isCleanup())
4066 for (unsigned i
= 0, e
= LPI
->getNumClauses(); i
!= e
; ++i
) {
4067 if (i
!= 0 || LPI
->isCleanup()) Out
<< "\n";
4068 if (LPI
->isCatch(i
))
4073 writeOperand(LPI
->getClause(i
), true);
4075 } else if (const auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(&I
)) {
4077 writeOperand(CatchSwitch
->getParentPad(), /*PrintType=*/false);
4080 for (const BasicBlock
*PadBB
: CatchSwitch
->handlers()) {
4083 writeOperand(PadBB
, /*PrintType=*/true);
4087 if (const BasicBlock
*UnwindDest
= CatchSwitch
->getUnwindDest())
4088 writeOperand(UnwindDest
, /*PrintType=*/true);
4091 } else if (const auto *FPI
= dyn_cast
<FuncletPadInst
>(&I
)) {
4093 writeOperand(FPI
->getParentPad(), /*PrintType=*/false);
4095 for (unsigned Op
= 0, NumOps
= FPI
->getNumArgOperands(); Op
< NumOps
;
4099 writeOperand(FPI
->getArgOperand(Op
), /*PrintType=*/true);
4102 } else if (isa
<ReturnInst
>(I
) && !Operand
) {
4104 } else if (const auto *CRI
= dyn_cast
<CatchReturnInst
>(&I
)) {
4106 writeOperand(CRI
->getOperand(0), /*PrintType=*/false);
4109 writeOperand(CRI
->getOperand(1), /*PrintType=*/true);
4110 } else if (const auto *CRI
= dyn_cast
<CleanupReturnInst
>(&I
)) {
4112 writeOperand(CRI
->getOperand(0), /*PrintType=*/false);
4115 if (CRI
->hasUnwindDest())
4116 writeOperand(CRI
->getOperand(1), /*PrintType=*/true);
4119 } else if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
4120 // Print the calling convention being used.
4121 if (CI
->getCallingConv() != CallingConv::C
) {
4123 PrintCallingConv(CI
->getCallingConv(), Out
);
4126 Operand
= CI
->getCalledOperand();
4127 FunctionType
*FTy
= CI
->getFunctionType();
4128 Type
*RetTy
= FTy
->getReturnType();
4129 const AttributeList
&PAL
= CI
->getAttributes();
4131 if (PAL
.hasRetAttrs())
4132 Out
<< ' ' << PAL
.getAsString(AttributeList::ReturnIndex
);
4134 // Only print addrspace(N) if necessary:
4135 maybePrintCallAddrSpace(Operand
, &I
, Out
);
4137 // If possible, print out the short form of the call instruction. We can
4138 // only do this if the first argument is a pointer to a nonvararg function,
4139 // and if the return type is not a pointer to a function.
4142 TypePrinter
.print(FTy
->isVarArg() ? FTy
: RetTy
, Out
);
4144 writeOperand(Operand
, false);
4146 for (unsigned op
= 0, Eop
= CI
->getNumArgOperands(); op
< Eop
; ++op
) {
4149 writeParamOperand(CI
->getArgOperand(op
), PAL
.getParamAttrs(op
));
4152 // Emit an ellipsis if this is a musttail call in a vararg function. This
4153 // is only to aid readability, musttail calls forward varargs by default.
4154 if (CI
->isMustTailCall() && CI
->getParent() &&
4155 CI
->getParent()->getParent() &&
4156 CI
->getParent()->getParent()->isVarArg())
4160 if (PAL
.hasFnAttrs())
4161 Out
<< " #" << Machine
.getAttributeGroupSlot(PAL
.getFnAttrs());
4163 writeOperandBundles(CI
);
4164 } else if (const InvokeInst
*II
= dyn_cast
<InvokeInst
>(&I
)) {
4165 Operand
= II
->getCalledOperand();
4166 FunctionType
*FTy
= II
->getFunctionType();
4167 Type
*RetTy
= FTy
->getReturnType();
4168 const AttributeList
&PAL
= II
->getAttributes();
4170 // Print the calling convention being used.
4171 if (II
->getCallingConv() != CallingConv::C
) {
4173 PrintCallingConv(II
->getCallingConv(), Out
);
4176 if (PAL
.hasRetAttrs())
4177 Out
<< ' ' << PAL
.getAsString(AttributeList::ReturnIndex
);
4179 // Only print addrspace(N) if necessary:
4180 maybePrintCallAddrSpace(Operand
, &I
, Out
);
4182 // If possible, print out the short form of the invoke instruction. We can
4183 // only do this if the first argument is a pointer to a nonvararg function,
4184 // and if the return type is not a pointer to a function.
4187 TypePrinter
.print(FTy
->isVarArg() ? FTy
: RetTy
, Out
);
4189 writeOperand(Operand
, false);
4191 for (unsigned op
= 0, Eop
= II
->getNumArgOperands(); op
< Eop
; ++op
) {
4194 writeParamOperand(II
->getArgOperand(op
), PAL
.getParamAttrs(op
));
4198 if (PAL
.hasFnAttrs())
4199 Out
<< " #" << Machine
.getAttributeGroupSlot(PAL
.getFnAttrs());
4201 writeOperandBundles(II
);
4204 writeOperand(II
->getNormalDest(), true);
4206 writeOperand(II
->getUnwindDest(), true);
4207 } else if (const CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(&I
)) {
4208 Operand
= CBI
->getCalledOperand();
4209 FunctionType
*FTy
= CBI
->getFunctionType();
4210 Type
*RetTy
= FTy
->getReturnType();
4211 const AttributeList
&PAL
= CBI
->getAttributes();
4213 // Print the calling convention being used.
4214 if (CBI
->getCallingConv() != CallingConv::C
) {
4216 PrintCallingConv(CBI
->getCallingConv(), Out
);
4219 if (PAL
.hasRetAttrs())
4220 Out
<< ' ' << PAL
.getAsString(AttributeList::ReturnIndex
);
4222 // If possible, print out the short form of the callbr instruction. We can
4223 // only do this if the first argument is a pointer to a nonvararg function,
4224 // and if the return type is not a pointer to a function.
4227 TypePrinter
.print(FTy
->isVarArg() ? FTy
: RetTy
, Out
);
4229 writeOperand(Operand
, false);
4231 for (unsigned op
= 0, Eop
= CBI
->getNumArgOperands(); op
< Eop
; ++op
) {
4234 writeParamOperand(CBI
->getArgOperand(op
), PAL
.getParamAttrs(op
));
4238 if (PAL
.hasFnAttrs())
4239 Out
<< " #" << Machine
.getAttributeGroupSlot(PAL
.getFnAttrs());
4241 writeOperandBundles(CBI
);
4244 writeOperand(CBI
->getDefaultDest(), true);
4246 for (unsigned i
= 0, e
= CBI
->getNumIndirectDests(); i
!= e
; ++i
) {
4249 writeOperand(CBI
->getIndirectDest(i
), true);
4252 } else if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(&I
)) {
4254 if (AI
->isUsedWithInAlloca())
4256 if (AI
->isSwiftError())
4257 Out
<< "swifterror ";
4258 TypePrinter
.print(AI
->getAllocatedType(), Out
);
4260 // Explicitly write the array size if the code is broken, if it's an array
4261 // allocation, or if the type is not canonical for scalar allocations. The
4262 // latter case prevents the type from mutating when round-tripping through
4264 if (!AI
->getArraySize() || AI
->isArrayAllocation() ||
4265 !AI
->getArraySize()->getType()->isIntegerTy(32)) {
4267 writeOperand(AI
->getArraySize(), true);
4269 if (AI
->getAlignment()) {
4270 Out
<< ", align " << AI
->getAlignment();
4273 unsigned AddrSpace
= AI
->getType()->getAddressSpace();
4274 if (AddrSpace
!= 0) {
4275 Out
<< ", addrspace(" << AddrSpace
<< ')';
4277 } else if (isa
<CastInst
>(I
)) {
4280 writeOperand(Operand
, true); // Work with broken code
4283 TypePrinter
.print(I
.getType(), Out
);
4284 } else if (isa
<VAArgInst
>(I
)) {
4287 writeOperand(Operand
, true); // Work with broken code
4290 TypePrinter
.print(I
.getType(), Out
);
4291 } else if (Operand
) { // Print the normal way.
4292 if (const auto *GEP
= dyn_cast
<GetElementPtrInst
>(&I
)) {
4294 TypePrinter
.print(GEP
->getSourceElementType(), Out
);
4296 } else if (const auto *LI
= dyn_cast
<LoadInst
>(&I
)) {
4298 TypePrinter
.print(LI
->getType(), Out
);
4302 // PrintAllTypes - Instructions who have operands of all the same type
4303 // omit the type from all but the first operand. If the instruction has
4304 // different type operands (for example br), then they are all printed.
4305 bool PrintAllTypes
= false;
4306 Type
*TheType
= Operand
->getType();
4308 // Select, Store and ShuffleVector always print all types.
4309 if (isa
<SelectInst
>(I
) || isa
<StoreInst
>(I
) || isa
<ShuffleVectorInst
>(I
)
4310 || isa
<ReturnInst
>(I
)) {
4311 PrintAllTypes
= true;
4313 for (unsigned i
= 1, E
= I
.getNumOperands(); i
!= E
; ++i
) {
4314 Operand
= I
.getOperand(i
);
4315 // note that Operand shouldn't be null, but the test helps make dump()
4316 // more tolerant of malformed IR
4317 if (Operand
&& Operand
->getType() != TheType
) {
4318 PrintAllTypes
= true; // We have differing types! Print them all!
4324 if (!PrintAllTypes
) {
4326 TypePrinter
.print(TheType
, Out
);
4330 for (unsigned i
= 0, E
= I
.getNumOperands(); i
!= E
; ++i
) {
4332 writeOperand(I
.getOperand(i
), PrintAllTypes
);
4336 // Print atomic ordering/alignment for memory operations
4337 if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(&I
)) {
4339 writeAtomic(LI
->getContext(), LI
->getOrdering(), LI
->getSyncScopeID());
4340 if (LI
->getAlignment())
4341 Out
<< ", align " << LI
->getAlignment();
4342 } else if (const StoreInst
*SI
= dyn_cast
<StoreInst
>(&I
)) {
4344 writeAtomic(SI
->getContext(), SI
->getOrdering(), SI
->getSyncScopeID());
4345 if (SI
->getAlignment())
4346 Out
<< ", align " << SI
->getAlignment();
4347 } else if (const AtomicCmpXchgInst
*CXI
= dyn_cast
<AtomicCmpXchgInst
>(&I
)) {
4348 writeAtomicCmpXchg(CXI
->getContext(), CXI
->getSuccessOrdering(),
4349 CXI
->getFailureOrdering(), CXI
->getSyncScopeID());
4350 Out
<< ", align " << CXI
->getAlign().value();
4351 } else if (const AtomicRMWInst
*RMWI
= dyn_cast
<AtomicRMWInst
>(&I
)) {
4352 writeAtomic(RMWI
->getContext(), RMWI
->getOrdering(),
4353 RMWI
->getSyncScopeID());
4354 Out
<< ", align " << RMWI
->getAlign().value();
4355 } else if (const FenceInst
*FI
= dyn_cast
<FenceInst
>(&I
)) {
4356 writeAtomic(FI
->getContext(), FI
->getOrdering(), FI
->getSyncScopeID());
4357 } else if (const ShuffleVectorInst
*SVI
= dyn_cast
<ShuffleVectorInst
>(&I
)) {
4358 PrintShuffleMask(Out
, SVI
->getType(), SVI
->getShuffleMask());
4361 // Print Metadata info.
4362 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> InstMD
;
4363 I
.getAllMetadata(InstMD
);
4364 printMetadataAttachments(InstMD
, ", ");
4366 // Print a nice comment.
4367 printInfoComment(I
);
4370 void AssemblyWriter::printMetadataAttachments(
4371 const SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &MDs
,
4372 StringRef Separator
) {
4376 if (MDNames
.empty())
4377 MDs
[0].second
->getContext().getMDKindNames(MDNames
);
4379 for (const auto &I
: MDs
) {
4380 unsigned Kind
= I
.first
;
4382 if (Kind
< MDNames
.size()) {
4384 printMetadataIdentifier(MDNames
[Kind
], Out
);
4386 Out
<< "!<unknown kind #" << Kind
<< ">";
4388 WriteAsOperandInternal(Out
, I
.second
, &TypePrinter
, &Machine
, TheModule
);
4392 void AssemblyWriter::writeMDNode(unsigned Slot
, const MDNode
*Node
) {
4393 Out
<< '!' << Slot
<< " = ";
4394 printMDNodeBody(Node
);
4398 void AssemblyWriter::writeAllMDNodes() {
4399 SmallVector
<const MDNode
*, 16> Nodes
;
4400 Nodes
.resize(Machine
.mdn_size());
4401 for (auto &I
: llvm::make_range(Machine
.mdn_begin(), Machine
.mdn_end()))
4402 Nodes
[I
.second
] = cast
<MDNode
>(I
.first
);
4404 for (unsigned i
= 0, e
= Nodes
.size(); i
!= e
; ++i
) {
4405 writeMDNode(i
, Nodes
[i
]);
4409 void AssemblyWriter::printMDNodeBody(const MDNode
*Node
) {
4410 WriteMDNodeBodyInternal(Out
, Node
, &TypePrinter
, &Machine
, TheModule
);
4413 void AssemblyWriter::writeAttribute(const Attribute
&Attr
, bool InAttrGroup
) {
4414 if (!Attr
.isTypeAttribute()) {
4415 Out
<< Attr
.getAsString(InAttrGroup
);
4419 Out
<< Attribute::getNameFromAttrKind(Attr
.getKindAsEnum());
4420 if (Type
*Ty
= Attr
.getValueAsType()) {
4422 TypePrinter
.print(Ty
, Out
);
4427 void AssemblyWriter::writeAttributeSet(const AttributeSet
&AttrSet
,
4429 bool FirstAttr
= true;
4430 for (const auto &Attr
: AttrSet
) {
4433 writeAttribute(Attr
, InAttrGroup
);
4438 void AssemblyWriter::writeAllAttributeGroups() {
4439 std::vector
<std::pair
<AttributeSet
, unsigned>> asVec
;
4440 asVec
.resize(Machine
.as_size());
4442 for (auto &I
: llvm::make_range(Machine
.as_begin(), Machine
.as_end()))
4443 asVec
[I
.second
] = I
;
4445 for (const auto &I
: asVec
)
4446 Out
<< "attributes #" << I
.second
<< " = { "
4447 << I
.first
.getAsString(true) << " }\n";
4450 void AssemblyWriter::printUseListOrder(const Value
*V
,
4451 const std::vector
<unsigned> &Shuffle
) {
4452 bool IsInFunction
= Machine
.getFunction();
4456 Out
<< "uselistorder";
4457 if (const BasicBlock
*BB
= IsInFunction
? nullptr : dyn_cast
<BasicBlock
>(V
)) {
4459 writeOperand(BB
->getParent(), false);
4461 writeOperand(BB
, false);
4464 writeOperand(V
, true);
4468 assert(Shuffle
.size() >= 2 && "Shuffle too small");
4470 for (unsigned I
= 1, E
= Shuffle
.size(); I
!= E
; ++I
)
4471 Out
<< ", " << Shuffle
[I
];
4475 void AssemblyWriter::printUseLists(const Function
*F
) {
4476 auto It
= UseListOrders
.find(F
);
4477 if (It
== UseListOrders
.end())
4480 Out
<< "\n; uselistorder directives\n";
4481 for (const auto &Pair
: It
->second
)
4482 printUseListOrder(Pair
.first
, Pair
.second
);
4485 //===----------------------------------------------------------------------===//
4486 // External Interface declarations
4487 //===----------------------------------------------------------------------===//
4489 void Function::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
,
4490 bool ShouldPreserveUseListOrder
,
4491 bool IsForDebug
) const {
4492 SlotTracker
SlotTable(this->getParent());
4493 formatted_raw_ostream
OS(ROS
);
4494 AssemblyWriter
W(OS
, SlotTable
, this->getParent(), AAW
,
4496 ShouldPreserveUseListOrder
);
4497 W
.printFunction(this);
4500 void BasicBlock::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
,
4501 bool ShouldPreserveUseListOrder
,
4502 bool IsForDebug
) const {
4503 SlotTracker
SlotTable(this->getParent());
4504 formatted_raw_ostream
OS(ROS
);
4505 AssemblyWriter
W(OS
, SlotTable
, this->getModule(), AAW
,
4507 ShouldPreserveUseListOrder
);
4508 W
.printBasicBlock(this);
4511 void Module::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
,
4512 bool ShouldPreserveUseListOrder
, bool IsForDebug
) const {
4513 SlotTracker
SlotTable(this);
4514 formatted_raw_ostream
OS(ROS
);
4515 AssemblyWriter
W(OS
, SlotTable
, this, AAW
, IsForDebug
,
4516 ShouldPreserveUseListOrder
);
4517 W
.printModule(this);
4520 void NamedMDNode::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4521 SlotTracker
SlotTable(getParent());
4522 formatted_raw_ostream
OS(ROS
);
4523 AssemblyWriter
W(OS
, SlotTable
, getParent(), nullptr, IsForDebug
);
4524 W
.printNamedMDNode(this);
4527 void NamedMDNode::print(raw_ostream
&ROS
, ModuleSlotTracker
&MST
,
4528 bool IsForDebug
) const {
4529 Optional
<SlotTracker
> LocalST
;
4530 SlotTracker
*SlotTable
;
4531 if (auto *ST
= MST
.getMachine())
4534 LocalST
.emplace(getParent());
4535 SlotTable
= &*LocalST
;
4538 formatted_raw_ostream
OS(ROS
);
4539 AssemblyWriter
W(OS
, *SlotTable
, getParent(), nullptr, IsForDebug
);
4540 W
.printNamedMDNode(this);
4543 void Comdat::print(raw_ostream
&ROS
, bool /*IsForDebug*/) const {
4544 PrintLLVMName(ROS
, getName(), ComdatPrefix
);
4545 ROS
<< " = comdat ";
4547 switch (getSelectionKind()) {
4551 case Comdat::ExactMatch
:
4552 ROS
<< "exactmatch";
4554 case Comdat::Largest
:
4557 case Comdat::NoDeduplicate
:
4558 ROS
<< "nodeduplicate";
4560 case Comdat::SameSize
:
4568 void Type::print(raw_ostream
&OS
, bool /*IsForDebug*/, bool NoDetails
) const {
4570 TP
.print(const_cast<Type
*>(this), OS
);
4575 // If the type is a named struct type, print the body as well.
4576 if (StructType
*STy
= dyn_cast
<StructType
>(const_cast<Type
*>(this)))
4577 if (!STy
->isLiteral()) {
4579 TP
.printStructBody(STy
, OS
);
4583 static bool isReferencingMDNode(const Instruction
&I
) {
4584 if (const auto *CI
= dyn_cast
<CallInst
>(&I
))
4585 if (Function
*F
= CI
->getCalledFunction())
4586 if (F
->isIntrinsic())
4587 for (auto &Op
: I
.operands())
4588 if (auto *V
= dyn_cast_or_null
<MetadataAsValue
>(Op
))
4589 if (isa
<MDNode
>(V
->getMetadata()))
4594 void Value::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4595 bool ShouldInitializeAllMetadata
= false;
4596 if (auto *I
= dyn_cast
<Instruction
>(this))
4597 ShouldInitializeAllMetadata
= isReferencingMDNode(*I
);
4598 else if (isa
<Function
>(this) || isa
<MetadataAsValue
>(this))
4599 ShouldInitializeAllMetadata
= true;
4601 ModuleSlotTracker
MST(getModuleFromVal(this), ShouldInitializeAllMetadata
);
4602 print(ROS
, MST
, IsForDebug
);
4605 void Value::print(raw_ostream
&ROS
, ModuleSlotTracker
&MST
,
4606 bool IsForDebug
) const {
4607 formatted_raw_ostream
OS(ROS
);
4608 SlotTracker
EmptySlotTable(static_cast<const Module
*>(nullptr));
4609 SlotTracker
&SlotTable
=
4610 MST
.getMachine() ? *MST
.getMachine() : EmptySlotTable
;
4611 auto incorporateFunction
= [&](const Function
*F
) {
4613 MST
.incorporateFunction(*F
);
4616 if (const Instruction
*I
= dyn_cast
<Instruction
>(this)) {
4617 incorporateFunction(I
->getParent() ? I
->getParent()->getParent() : nullptr);
4618 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(I
), nullptr, IsForDebug
);
4619 W
.printInstruction(*I
);
4620 } else if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(this)) {
4621 incorporateFunction(BB
->getParent());
4622 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(BB
), nullptr, IsForDebug
);
4623 W
.printBasicBlock(BB
);
4624 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(this)) {
4625 AssemblyWriter
W(OS
, SlotTable
, GV
->getParent(), nullptr, IsForDebug
);
4626 if (const GlobalVariable
*V
= dyn_cast
<GlobalVariable
>(GV
))
4628 else if (const Function
*F
= dyn_cast
<Function
>(GV
))
4631 W
.printIndirectSymbol(cast
<GlobalIndirectSymbol
>(GV
));
4632 } else if (const MetadataAsValue
*V
= dyn_cast
<MetadataAsValue
>(this)) {
4633 V
->getMetadata()->print(ROS
, MST
, getModuleFromVal(V
));
4634 } else if (const Constant
*C
= dyn_cast
<Constant
>(this)) {
4635 TypePrinting TypePrinter
;
4636 TypePrinter
.print(C
->getType(), OS
);
4638 WriteConstantInternal(OS
, C
, TypePrinter
, MST
.getMachine(), nullptr);
4639 } else if (isa
<InlineAsm
>(this) || isa
<Argument
>(this)) {
4640 this->printAsOperand(OS
, /* PrintType */ true, MST
);
4642 llvm_unreachable("Unknown value to print out!");
4646 /// Print without a type, skipping the TypePrinting object.
4648 /// \return \c true iff printing was successful.
4649 static bool printWithoutType(const Value
&V
, raw_ostream
&O
,
4650 SlotTracker
*Machine
, const Module
*M
) {
4651 if (V
.hasName() || isa
<GlobalValue
>(V
) ||
4652 (!isa
<Constant
>(V
) && !isa
<MetadataAsValue
>(V
))) {
4653 WriteAsOperandInternal(O
, &V
, nullptr, Machine
, M
);
4659 static void printAsOperandImpl(const Value
&V
, raw_ostream
&O
, bool PrintType
,
4660 ModuleSlotTracker
&MST
) {
4661 TypePrinting
TypePrinter(MST
.getModule());
4663 TypePrinter
.print(V
.getType(), O
);
4667 WriteAsOperandInternal(O
, &V
, &TypePrinter
, MST
.getMachine(),
4671 void Value::printAsOperand(raw_ostream
&O
, bool PrintType
,
4672 const Module
*M
) const {
4674 M
= getModuleFromVal(this);
4677 if (printWithoutType(*this, O
, nullptr, M
))
4680 SlotTracker
Machine(
4681 M
, /* ShouldInitializeAllMetadata */ isa
<MetadataAsValue
>(this));
4682 ModuleSlotTracker
MST(Machine
, M
);
4683 printAsOperandImpl(*this, O
, PrintType
, MST
);
4686 void Value::printAsOperand(raw_ostream
&O
, bool PrintType
,
4687 ModuleSlotTracker
&MST
) const {
4689 if (printWithoutType(*this, O
, MST
.getMachine(), MST
.getModule()))
4692 printAsOperandImpl(*this, O
, PrintType
, MST
);
4695 static void printMetadataImpl(raw_ostream
&ROS
, const Metadata
&MD
,
4696 ModuleSlotTracker
&MST
, const Module
*M
,
4697 bool OnlyAsOperand
) {
4698 formatted_raw_ostream
OS(ROS
);
4700 TypePrinting
TypePrinter(M
);
4702 WriteAsOperandInternal(OS
, &MD
, &TypePrinter
, MST
.getMachine(), M
,
4703 /* FromValue */ true);
4705 auto *N
= dyn_cast
<MDNode
>(&MD
);
4706 if (OnlyAsOperand
|| !N
|| isa
<DIExpression
>(MD
) || isa
<DIArgList
>(MD
))
4710 WriteMDNodeBodyInternal(OS
, N
, &TypePrinter
, MST
.getMachine(), M
);
4713 void Metadata::printAsOperand(raw_ostream
&OS
, const Module
*M
) const {
4714 ModuleSlotTracker
MST(M
, isa
<MDNode
>(this));
4715 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ true);
4718 void Metadata::printAsOperand(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
4719 const Module
*M
) const {
4720 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ true);
4723 void Metadata::print(raw_ostream
&OS
, const Module
*M
,
4724 bool /*IsForDebug*/) const {
4725 ModuleSlotTracker
MST(M
, isa
<MDNode
>(this));
4726 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ false);
4729 void Metadata::print(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
4730 const Module
*M
, bool /*IsForDebug*/) const {
4731 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ false);
4734 void ModuleSummaryIndex::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4735 SlotTracker
SlotTable(this);
4736 formatted_raw_ostream
OS(ROS
);
4737 AssemblyWriter
W(OS
, SlotTable
, this, IsForDebug
);
4738 W
.printModuleSummaryIndex();
4741 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType
&L
, unsigned LB
,
4742 unsigned UB
) const {
4743 SlotTracker
*ST
= MachineStorage
.get();
4747 for (auto &I
: llvm::make_range(ST
->mdn_begin(), ST
->mdn_end()))
4748 if (I
.second
>= LB
&& I
.second
< UB
)
4749 L
.push_back(std::make_pair(I
.second
, I
.first
));
4752 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4753 // Value::dump - allow easy printing of Values from the debugger.
4755 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4757 // Type::dump - allow easy printing of Types from the debugger.
4759 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4761 // Module::dump() - Allow printing of Modules from the debugger.
4763 void Module::dump() const {
4764 print(dbgs(), nullptr,
4765 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4768 // Allow printing of Comdats from the debugger.
4770 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4772 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4774 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4777 void Metadata::dump() const { dump(nullptr); }
4780 void Metadata::dump(const Module
*M
) const {
4781 print(dbgs(), M
, /*IsForDebug=*/true);
4785 // Allow printing of ModuleSummaryIndex from the debugger.
4787 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }