1//===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
12//
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.
15//
16//===----------------------------------------------------------------------===//
17
18#include "LLVMContextImpl.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/STLFunctionalExtras.h"
25#include "llvm/ADT/SmallPtrSet.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/DebugProgramInstruction.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalAlias.h"
47#include "llvm/IR/GlobalIFunc.h"
48#include "llvm/IR/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/Intrinsics.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/Metadata.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ModuleSlotTracker.h"
62#include "llvm/IR/ModuleSummaryIndex.h"
63#include "llvm/IR/Operator.h"
64#include "llvm/IR/Type.h"
65#include "llvm/IR/TypeFinder.h"
66#include "llvm/IR/TypedPointerType.h"
67#include "llvm/IR/Use.h"
68#include "llvm/IR/User.h"
69#include "llvm/IR/Value.h"
70#include "llvm/Support/AtomicOrdering.h"
71#include "llvm/Support/Casting.h"
72#include "llvm/Support/Compiler.h"
73#include "llvm/Support/Debug.h"
74#include "llvm/Support/ErrorHandling.h"
75#include "llvm/Support/FormattedStream.h"
76#include "llvm/Support/SaveAndRestore.h"
77#include "llvm/Support/raw_ostream.h"
78#include <cassert>
79#include <cctype>
80#include <cstddef>
81#include <cstdint>
82#include <iterator>
83#include <memory>
84#include <optional>
85#include <string>
86#include <tuple>
87#include <utility>
88#include <vector>
89
90using namespace llvm;
91
92// See https://llvm.org/docs/DebuggingLLVM.html for why these flags are useful.
93
94static cl::opt<bool>
95 PrintInstAddrs("print-inst-addrs", cl::Hidden,
96 cl::desc("Print addresses of instructions when dumping"));
97
98static cl::opt<bool> PrintInstDebugLocs(
99 "print-inst-debug-locs", cl::Hidden,
100 cl::desc("Pretty print debug locations of instructions when dumping"));
101
102static cl::opt<bool> PrintProfData(
103 "print-prof-data", cl::Hidden,
104 cl::desc("Pretty print perf data (branch weights, etc) when dumping"));
105
106static cl::opt<bool> PreserveAssemblyUseListOrder(
107 "preserve-ll-uselistorder", cl::Hidden, cl::init(Val: false),
108 cl::desc("Preserve use-list order when writing LLVM assembly."));
109
110static cl::opt<bool> PrintAddrspaceName("print-addrspace-name", cl::Hidden,
111 cl::init(Val: false),
112 cl::desc("Print address space names"));
113
114// Make virtual table appear in this compilation unit.
115AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
116
117//===----------------------------------------------------------------------===//
118// Helper Functions
119//===----------------------------------------------------------------------===//
120
121using OrderMap = MapVector<const Value *, unsigned>;
122
123using UseListOrderMap =
124 DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
125
126/// Look for a value that might be wrapped as metadata, e.g. a value in a
127/// metadata operand. Returns the input value as-is if it is not wrapped.
128static const Value *skipMetadataWrapper(const Value *V) {
129 if (const auto *MAV = dyn_cast<MetadataAsValue>(Val: V))
130 if (const auto *VAM = dyn_cast<ValueAsMetadata>(Val: MAV->getMetadata()))
131 return VAM->getValue();
132 return V;
133}
134
135static void orderValue(const Value *V, OrderMap &OM) {
136 if (OM.lookup(Key: V))
137 return;
138
139 if (const auto *C = dyn_cast<Constant>(Val: V)) {
140 if (isa<ConstantData>(Val: C))
141 return;
142
143 if (C->getNumOperands() && !isa<GlobalValue>(Val: C))
144 for (const Value *Op : C->operands())
145 if (!isa<BasicBlock>(Val: Op) && !isa<GlobalValue>(Val: Op))
146 orderValue(V: Op, OM);
147 }
148
149 // Note: we cannot cache this lookup above, since inserting into the map
150 // changes the map's size, and thus affects the other IDs.
151 unsigned ID = OM.size() + 1;
152 OM[V] = ID;
153}
154
155static OrderMap orderModule(const Module *M) {
156 OrderMap OM;
157
158 auto OrderConstantValue = [&OM](const Value *V) {
159 if (isa<Constant>(Val: V) || isa<InlineAsm>(Val: V))
160 orderValue(V, OM);
161 };
162
163 auto OrderConstantFromMetadata = [&](Metadata *MD) {
164 if (const auto *VAM = dyn_cast<ValueAsMetadata>(Val: MD)) {
165 OrderConstantValue(VAM->getValue());
166 } else if (const auto *AL = dyn_cast<DIArgList>(Val: MD)) {
167 for (const auto *VAM : AL->getArgs())
168 OrderConstantValue(VAM->getValue());
169 }
170 };
171
172 for (const GlobalVariable &G : M->globals()) {
173 if (G.hasInitializer())
174 if (!isa<GlobalValue>(Val: G.getInitializer()))
175 orderValue(V: G.getInitializer(), OM);
176 orderValue(V: &G, OM);
177 }
178 for (const GlobalAlias &A : M->aliases()) {
179 if (!isa<GlobalValue>(Val: A.getAliasee()))
180 orderValue(V: A.getAliasee(), OM);
181 orderValue(V: &A, OM);
182 }
183 for (const GlobalIFunc &I : M->ifuncs()) {
184 if (!isa<GlobalValue>(Val: I.getResolver()))
185 orderValue(V: I.getResolver(), OM);
186 orderValue(V: &I, OM);
187 }
188 for (const Function &F : *M) {
189 for (const Use &U : F.operands())
190 if (!isa<GlobalValue>(Val: U.get()))
191 orderValue(V: U.get(), OM);
192
193 orderValue(V: &F, OM);
194
195 if (F.isDeclaration())
196 continue;
197
198 for (const Argument &A : F.args())
199 orderValue(V: &A, OM);
200 for (const BasicBlock &BB : F) {
201 orderValue(V: &BB, OM);
202 for (const Instruction &I : BB) {
203 // Debug records can contain Value references, that can then contain
204 // Values disconnected from the rest of the Value hierachy, if wrapped
205 // in some kind of constant-expression. Find and order any Values that
206 // are wrapped in debug-info.
207 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) {
208 OrderConstantFromMetadata(DVR.getRawLocation());
209 if (DVR.isDbgAssign())
210 OrderConstantFromMetadata(DVR.getRawAddress());
211 }
212
213 for (const Value *Op : I.operands()) {
214 Op = skipMetadataWrapper(V: Op);
215 if ((isa<Constant>(Val: *Op) && !isa<GlobalValue>(Val: *Op)) ||
216 isa<InlineAsm>(Val: *Op))
217 orderValue(V: Op, OM);
218 }
219 orderValue(V: &I, OM);
220 }
221 }
222 }
223 return OM;
224}
225
226static std::vector<unsigned>
227predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
228 // Predict use-list order for this one.
229 using Entry = std::pair<const Use *, unsigned>;
230 SmallVector<Entry, 64> List;
231 for (const Use &U : V->uses())
232 // Check if this user will be serialized.
233 if (OM.lookup(Key: U.getUser()))
234 List.push_back(Elt: std::make_pair(x: &U, y: List.size()));
235
236 if (List.size() < 2)
237 // We may have lost some users.
238 return {};
239
240 // When referencing a value before its declaration, a temporary value is
241 // created, which will later be RAUWed with the actual value. This reverses
242 // the use list. This happens for all values apart from basic blocks.
243 bool GetsReversed = !isa<BasicBlock>(Val: V);
244 if (auto *BA = dyn_cast<BlockAddress>(Val: V))
245 ID = OM.lookup(Key: BA->getBasicBlock());
246 llvm::sort(C&: List, Comp: [&](const Entry &L, const Entry &R) {
247 const Use *LU = L.first;
248 const Use *RU = R.first;
249 if (LU == RU)
250 return false;
251
252 auto LID = OM.lookup(Key: LU->getUser());
253 auto RID = OM.lookup(Key: RU->getUser());
254
255 // If ID is 4, then expect: 7 6 5 1 2 3.
256 if (LID < RID) {
257 if (GetsReversed)
258 if (RID <= ID)
259 return true;
260 return false;
261 }
262 if (RID < LID) {
263 if (GetsReversed)
264 if (LID <= ID)
265 return false;
266 return true;
267 }
268
269 // LID and RID are equal, so we have different operands of the same user.
270 // Assume operands are added in order for all instructions.
271 if (GetsReversed)
272 if (LID <= ID)
273 return LU->getOperandNo() < RU->getOperandNo();
274 return LU->getOperandNo() > RU->getOperandNo();
275 });
276
277 if (llvm::is_sorted(Range&: List, C: llvm::less_second()))
278 // Order is already correct.
279 return {};
280
281 // Store the shuffle.
282 std::vector<unsigned> Shuffle(List.size());
283 for (size_t I = 0, E = List.size(); I != E; ++I)
284 Shuffle[I] = List[I].second;
285 return Shuffle;
286}
287
288static UseListOrderMap predictUseListOrder(const Module *M) {
289 OrderMap OM = orderModule(M);
290 UseListOrderMap ULOM;
291 for (const auto &Pair : OM) {
292 const Value *V = Pair.first;
293 if (V->use_empty() || std::next(x: V->use_begin()) == V->use_end())
294 continue;
295
296 std::vector<unsigned> Shuffle =
297 predictValueUseListOrder(V, ID: Pair.second, OM);
298 if (Shuffle.empty())
299 continue;
300
301 const Function *F = nullptr;
302 if (auto *I = dyn_cast<Instruction>(Val: V))
303 F = I->getFunction();
304 if (auto *A = dyn_cast<Argument>(Val: V))
305 F = A->getParent();
306 if (auto *BB = dyn_cast<BasicBlock>(Val: V))
307 F = BB->getParent();
308 ULOM[F][V] = std::move(Shuffle);
309 }
310 return ULOM;
311}
312
313static const Module *getModuleFromVal(const Value *V) {
314 if (const auto *MA = dyn_cast<Argument>(Val: V))
315 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
316
317 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
318 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
319
320 if (const auto *I = dyn_cast<Instruction>(Val: V)) {
321 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
322 return M ? M->getParent() : nullptr;
323 }
324
325 if (const auto *GV = dyn_cast<GlobalValue>(Val: V))
326 return GV->getParent();
327
328 if (const auto *MAV = dyn_cast<MetadataAsValue>(Val: V)) {
329 for (const User *U : MAV->users())
330 if (isa<Instruction>(Val: U))
331 if (const Module *M = getModuleFromVal(V: U))
332 return M;
333 return nullptr;
334 }
335
336 return nullptr;
337}
338
339static const Module *getModuleFromDPI(const DbgMarker *Marker) {
340 const Function *M =
341 Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
342 return M ? M->getParent() : nullptr;
343}
344
345static const Module *getModuleFromDPI(const DbgRecord *DR) {
346 return DR->getMarker() ? getModuleFromDPI(Marker: DR->getMarker()) : nullptr;
347}
348
349static void printCallingConv(unsigned cc, raw_ostream &Out) {
350 switch (cc) {
351 default: Out << "cc" << cc; break;
352 case CallingConv::Fast: Out << "fastcc"; break;
353 case CallingConv::Cold: Out << "coldcc"; break;
354 case CallingConv::AnyReg: Out << "anyregcc"; break;
355 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
356 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
357 case CallingConv::PreserveNone: Out << "preserve_nonecc"; break;
358 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
359 case CallingConv::GHC: Out << "ghccc"; break;
360 case CallingConv::Tail: Out << "tailcc"; break;
361 case CallingConv::GRAAL: Out << "graalcc"; break;
362 case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
363 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
364 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
365 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
366 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
367 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
368 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
369 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
370 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
371 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
372 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
373 case CallingConv::AArch64_SVE_VectorCall:
374 Out << "aarch64_sve_vector_pcs";
375 break;
376 case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
377 Out << "aarch64_sme_preservemost_from_x0";
378 break;
379 case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1:
380 Out << "aarch64_sme_preservemost_from_x1";
381 break;
382 case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
383 Out << "aarch64_sme_preservemost_from_x2";
384 break;
385 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
386 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
387 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
388 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
389 case CallingConv::PTX_Device: Out << "ptx_device"; break;
390 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
391 case CallingConv::Win64: Out << "win64cc"; break;
392 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
393 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
394 case CallingConv::Swift: Out << "swiftcc"; break;
395 case CallingConv::SwiftTail: Out << "swifttailcc"; break;
396 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
397 case CallingConv::DUMMY_HHVM:
398 Out << "hhvmcc";
399 break;
400 case CallingConv::DUMMY_HHVM_C:
401 Out << "hhvm_ccc";
402 break;
403 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
404 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
405 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
406 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
407 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
408 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
409 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
410 case CallingConv::AMDGPU_CS_Chain:
411 Out << "amdgpu_cs_chain";
412 break;
413 case CallingConv::AMDGPU_CS_ChainPreserve:
414 Out << "amdgpu_cs_chain_preserve";
415 break;
416 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
417 case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
418 case CallingConv::AMDGPU_Gfx_WholeWave:
419 Out << "amdgpu_gfx_whole_wave";
420 break;
421 case CallingConv::M68k_RTD: Out << "m68k_rtdcc"; break;
422 case CallingConv::RISCV_VectorCall:
423 Out << "riscv_vector_cc";
424 break;
425#define CC_VLS_CASE(ABI_VLEN) \
426 case CallingConv::RISCV_VLSCall_##ABI_VLEN: \
427 Out << "riscv_vls_cc(" #ABI_VLEN ")"; \
428 break;
429 CC_VLS_CASE(32)
430 CC_VLS_CASE(64)
431 CC_VLS_CASE(128)
432 CC_VLS_CASE(256)
433 CC_VLS_CASE(512)
434 CC_VLS_CASE(1024)
435 CC_VLS_CASE(2048)
436 CC_VLS_CASE(4096)
437 CC_VLS_CASE(8192)
438 CC_VLS_CASE(16384)
439 CC_VLS_CASE(32768)
440 CC_VLS_CASE(65536)
441#undef CC_VLS_CASE
442 case CallingConv::CHERIoT_CompartmentCall:
443 Out << "cheriot_compartmentcallcc";
444 break;
445 case CallingConv::CHERIoT_CompartmentCallee:
446 Out << "cheriot_compartmentcalleecc";
447 break;
448 case CallingConv::CHERIoT_LibraryCall:
449 Out << "cheriot_librarycallcc";
450 break;
451 }
452}
453
454enum PrefixType {
455 GlobalPrefix,
456 ComdatPrefix,
457 LabelPrefix,
458 LocalPrefix,
459 NoPrefix
460};
461
462void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
463 assert(!Name.empty() && "Cannot get empty name!");
464
465 // Scan the name to see if it needs quotes first.
466 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
467 if (!NeedsQuotes) {
468 for (unsigned char C : Name) {
469 // By making this unsigned, the value passed in to isalnum will always be
470 // in the range 0-255. This is important when building with MSVC because
471 // its implementation will assert. This situation can arise when dealing
472 // with UTF-8 multibyte characters.
473 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
474 NeedsQuotes = true;
475 break;
476 }
477 }
478 }
479
480 // If we didn't need any quotes, just write out the name in one blast.
481 if (!NeedsQuotes) {
482 OS << Name;
483 return;
484 }
485
486 // Okay, we need quotes. Output the quotes and escape any scary characters as
487 // needed.
488 OS << '"';
489 printEscapedString(Name, Out&: OS);
490 OS << '"';
491}
492
493/// Turn the specified name into an 'LLVM name', which is either prefixed with %
494/// (if the string only contains simple characters) or is surrounded with ""'s
495/// (if it has special chars in it). Print it out.
496static void printLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
497 switch (Prefix) {
498 case NoPrefix:
499 break;
500 case GlobalPrefix:
501 OS << '@';
502 break;
503 case ComdatPrefix:
504 OS << '$';
505 break;
506 case LabelPrefix:
507 break;
508 case LocalPrefix:
509 OS << '%';
510 break;
511 }
512 printLLVMNameWithoutPrefix(OS, Name);
513}
514
515/// Turn the specified name into an 'LLVM name', which is either prefixed with %
516/// (if the string only contains simple characters) or is surrounded with ""'s
517/// (if it has special chars in it). Print it out.
518static void printLLVMName(raw_ostream &OS, const Value *V) {
519 printLLVMName(OS, Name: V->getName(),
520 Prefix: isa<GlobalValue>(Val: V) ? GlobalPrefix : LocalPrefix);
521}
522
523static void printShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
524 Out << ", <";
525 if (isa<ScalableVectorType>(Val: Ty))
526 Out << "vscale x ";
527 Out << Mask.size() << " x i32> ";
528 if (all_of(Range&: Mask, P: equal_to(Arg: 0))) {
529 Out << "zeroinitializer";
530 } else if (all_of(Range&: Mask, P: equal_to(Arg: PoisonMaskElem))) {
531 Out << "poison";
532 } else {
533 Out << "<";
534 ListSeparator LS;
535 for (int Elt : Mask) {
536 Out << LS << "i32 ";
537 if (Elt == PoisonMaskElem)
538 Out << "poison";
539 else
540 Out << Elt;
541 }
542 Out << ">";
543 }
544}
545
546namespace {
547
548class TypePrinting {
549public:
550 TypePrinting(const Module *M = nullptr)
551 : M(M), TypesIncorporated(M == nullptr) {}
552
553 TypePrinting(const TypePrinting &) = delete;
554 TypePrinting &operator=(const TypePrinting &) = delete;
555
556 /// The named types that are used by the current module.
557 TypeFinder &getNamedTypes();
558
559 /// The numbered types, number to type mapping.
560 std::vector<StructType *> &getNumberedTypes();
561
562 bool empty();
563
564 void print(Type *Ty, raw_ostream &OS);
565
566 void printStructBody(StructType *Ty, raw_ostream &OS);
567
568private:
569 void incorporateTypes();
570
571 /// A module to process lazily.
572 const Module *M;
573 bool TypesIncorporated;
574
575 TypeFinder NamedTypes;
576
577 // The numbered types, along with their value.
578 DenseMap<StructType *, unsigned> Type2Number;
579
580 std::vector<StructType *> NumberedTypes;
581};
582
583} // end anonymous namespace
584
585TypeFinder &TypePrinting::getNamedTypes() {
586 incorporateTypes();
587 return NamedTypes;
588}
589
590std::vector<StructType *> &TypePrinting::getNumberedTypes() {
591 incorporateTypes();
592
593 // We know all the numbers that each type is used and we know that it is a
594 // dense assignment. Convert the map to an index table, if it's not done
595 // already (judging from the sizes):
596 if (NumberedTypes.size() == Type2Number.size())
597 return NumberedTypes;
598
599 NumberedTypes.resize(new_size: Type2Number.size());
600 for (const auto &P : Type2Number) {
601 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
602 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
603 NumberedTypes[P.second] = P.first;
604 }
605 return NumberedTypes;
606}
607
608bool TypePrinting::empty() {
609 incorporateTypes();
610 return NamedTypes.empty() && Type2Number.empty();
611}
612
613void TypePrinting::incorporateTypes() {
614 if (TypesIncorporated)
615 return;
616
617 NamedTypes.run(M: *M, onlyNamed: false);
618 TypesIncorporated = true;
619
620 // The list of struct types we got back includes all the struct types, split
621 // the unnamed ones out to a numbering and remove the anonymous structs.
622 unsigned NextNumber = 0;
623
624 std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
625 for (StructType *STy : NamedTypes) {
626 // Ignore anonymous types.
627 if (STy->isLiteral())
628 continue;
629
630 if (STy->getName().empty())
631 Type2Number[STy] = NextNumber++;
632 else
633 *NextToUse++ = STy;
634 }
635
636 NamedTypes.erase(I: NextToUse, E: NamedTypes.end());
637}
638
639static void printAddressSpace(const Module *M, unsigned AS, raw_ostream &OS,
640 StringRef Prefix = " ", StringRef Suffix = "",
641 bool ForcePrint = false) {
642 if (AS == 0 && !ForcePrint)
643 return;
644 OS << Prefix << "addrspace(";
645 StringRef ASName =
646 PrintAddrspaceName && M ? M->getDataLayout().getAddressSpaceName(AS) : "";
647 if (!ASName.empty())
648 OS << "\"" << ASName << "\"";
649 else
650 OS << AS;
651 OS << ")" << Suffix;
652}
653
654/// Write the specified type to the specified raw_ostream, making use of type
655/// names or up references to shorten the type name where possible.
656void TypePrinting::print(Type *Ty, raw_ostream &OS) {
657 switch (Ty->getTypeID()) {
658 case Type::VoidTyID: OS << "void"; return;
659 case Type::HalfTyID: OS << "half"; return;
660 case Type::BFloatTyID: OS << "bfloat"; return;
661 case Type::FloatTyID: OS << "float"; return;
662 case Type::DoubleTyID: OS << "double"; return;
663 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
664 case Type::FP128TyID: OS << "fp128"; return;
665 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
666 case Type::LabelTyID: OS << "label"; return;
667 case Type::MetadataTyID:
668 OS << "metadata";
669 return;
670 case Type::X86_AMXTyID: OS << "x86_amx"; return;
671 case Type::TokenTyID: OS << "token"; return;
672 case Type::ByteTyID:
673 OS << 'b' << Ty->getByteBitWidth();
674 return;
675 case Type::IntegerTyID:
676 OS << 'i' << cast<IntegerType>(Val: Ty)->getBitWidth();
677 return;
678
679 case Type::FunctionTyID: {
680 FunctionType *FTy = cast<FunctionType>(Val: Ty);
681 print(Ty: FTy->getReturnType(), OS);
682 OS << " (";
683 ListSeparator LS;
684 for (Type *Ty : FTy->params()) {
685 OS << LS;
686 print(Ty, OS);
687 }
688 if (FTy->isVarArg())
689 OS << LS << "...";
690 OS << ')';
691 return;
692 }
693 case Type::StructTyID: {
694 StructType *STy = cast<StructType>(Val: Ty);
695
696 if (STy->isLiteral())
697 return printStructBody(Ty: STy, OS);
698
699 if (!STy->getName().empty())
700 return printLLVMName(OS, Name: STy->getName(), Prefix: LocalPrefix);
701
702 incorporateTypes();
703 const auto I = Type2Number.find(Val: STy);
704 if (I != Type2Number.end())
705 OS << '%' << I->second;
706 else // Not enumerated, print the hex address.
707 OS << "%\"type " << STy << '\"';
708 return;
709 }
710 case Type::PointerTyID: {
711 PointerType *PTy = cast<PointerType>(Val: Ty);
712 OS << "ptr";
713 printAddressSpace(M, AS: PTy->getAddressSpace(), OS);
714 return;
715 }
716 case Type::ArrayTyID: {
717 ArrayType *ATy = cast<ArrayType>(Val: Ty);
718 OS << '[' << ATy->getNumElements() << " x ";
719 print(Ty: ATy->getElementType(), OS);
720 OS << ']';
721 return;
722 }
723 case Type::FixedVectorTyID:
724 case Type::ScalableVectorTyID: {
725 VectorType *PTy = cast<VectorType>(Val: Ty);
726 ElementCount EC = PTy->getElementCount();
727 OS << "<";
728 if (EC.isScalable())
729 OS << "vscale x ";
730 OS << EC.getKnownMinValue() << " x ";
731 print(Ty: PTy->getElementType(), OS);
732 OS << '>';
733 return;
734 }
735 case Type::TypedPointerTyID: {
736 TypedPointerType *TPTy = cast<TypedPointerType>(Val: Ty);
737 OS << "typedptr(" << *TPTy->getElementType() << ", "
738 << TPTy->getAddressSpace() << ")";
739 return;
740 }
741 case Type::TargetExtTyID:
742 TargetExtType *TETy = cast<TargetExtType>(Val: Ty);
743 OS << "target(\"";
744 printEscapedString(Name: Ty->getTargetExtName(), Out&: OS);
745 OS << "\"";
746 for (Type *Inner : TETy->type_params()) {
747 OS << ", ";
748 Inner->print(O&: OS, /*IsForDebug=*/false, /*NoDetails=*/true);
749 }
750 for (unsigned IntParam : TETy->int_params())
751 OS << ", " << IntParam;
752 OS << ")";
753 return;
754 }
755 llvm_unreachable("Invalid TypeID");
756}
757
758void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
759 if (STy->isOpaque()) {
760 OS << "opaque";
761 return;
762 }
763
764 if (STy->isPacked())
765 OS << '<';
766
767 if (STy->getNumElements() == 0) {
768 OS << "{}";
769 } else {
770 OS << "{ ";
771 ListSeparator LS;
772 for (Type *Ty : STy->elements()) {
773 OS << LS;
774 print(Ty, OS);
775 }
776
777 OS << " }";
778 }
779 if (STy->isPacked())
780 OS << '>';
781}
782
783AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
784
785//===----------------------------------------------------------------------===//
786// SlotTracker Class: Enumerate slot numbers for unnamed values
787//===----------------------------------------------------------------------===//
788/// This class provides computation of slot numbers for LLVM Assembly writing.
789///
790class llvm::SlotTracker : public AbstractSlotTrackerStorage {
791public:
792 /// ValueMap - A mapping of Values to slot numbers.
793 using ValueMap = DenseMap<const Value *, unsigned>;
794
795private:
796 /// TheModule - The module for which we are holding slot numbers.
797 const Module* TheModule;
798
799 /// TheFunction - The function for which we are holding slot numbers.
800 const Function* TheFunction = nullptr;
801 bool FunctionProcessed = false;
802 bool ShouldTrackMetadataDefinitions;
803
804 std::function<void(AbstractSlotTrackerStorage *, const Module *)>
805 ProcessModuleHookFn;
806 std::function<void(AbstractSlotTrackerStorage *, const Function *)>
807 ProcessFunctionHookFn;
808
809 /// The summary index for which we are holding slot numbers.
810 const ModuleSummaryIndex *TheIndex = nullptr;
811
812 /// mMap - The slot map for the module level data.
813 ValueMap mMap;
814 unsigned mNext = 0;
815
816 /// fMap - The slot map for the function level data.
817 ValueMap fMap;
818 unsigned fNext = 0;
819
820 /// mdnMap - Map for MDNodes.
821 DenseMap<const MDNode *, unsigned> mdnMap;
822 /// asMap - The slot map for attribute sets.
823 DenseMap<AttributeSet, unsigned> asMap;
824 unsigned asNext = 0;
825
826 /// ModulePathMap - The slot map for Module paths used in the summary index.
827 StringMap<unsigned> ModulePathMap;
828 unsigned ModulePathNext = 0;
829
830 /// GUIDMap - The slot map for GUIDs used in the summary index.
831 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
832 unsigned GUIDNext = 0;
833
834 /// TypeIdMap - The slot map for type ids used in the summary index.
835 StringMap<unsigned> TypeIdMap;
836 unsigned TypeIdNext = 0;
837
838 /// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids
839 /// used in the summary index.
840 StringMap<unsigned> TypeIdCompatibleVtableMap;
841 unsigned TypeIdCompatibleVtableNext = 0;
842
843public:
844 /// Construct from a module.
845 ///
846 explicit SlotTracker(const Module *M,
847 bool ShouldTrackMetadataDefinitions = false);
848
849 /// Construct from a function, starting out in incorp state.
850 ///
851 explicit SlotTracker(const Function *F);
852
853 /// Construct from a module summary index.
854 explicit SlotTracker(const ModuleSummaryIndex *Index);
855
856 SlotTracker(const SlotTracker &) = delete;
857 SlotTracker &operator=(const SlotTracker &) = delete;
858
859 ~SlotTracker() override = default;
860
861 void setProcessHook(
862 std::function<void(AbstractSlotTrackerStorage *, const Module *)>);
863 void setProcessHook(
864 std::function<void(AbstractSlotTrackerStorage *, const Function *)>);
865
866 void createMetadataSlot(const MDNode *N) override;
867
868 /// Return the slot number of the specified value in it's type
869 /// plane. If something is not in the SlotTracker, return -1.
870 int getLocalSlot(const Value *V);
871 int getGlobalSlot(const GlobalValue *V);
872 int getMetadataSlot(const MDNode *N) override;
873 int getAttributeGroupSlot(AttributeSet AS);
874 int getModulePathSlot(StringRef Path);
875 int getGUIDSlot(GlobalValue::GUID GUID);
876 int getTypeIdSlot(StringRef Id);
877 int getTypeIdCompatibleVtableSlot(StringRef Id);
878
879 /// If you'd like to deal with a function instead of just a module, use
880 /// this method to get its data into the SlotTracker.
881 void incorporateFunction(const Function *F) {
882 TheFunction = F;
883 FunctionProcessed = false;
884 }
885
886 const Function *getFunction() const { return TheFunction; }
887
888 /// After calling incorporateFunction, use this method to remove the
889 /// most recently incorporated function from the SlotTracker. This
890 /// will reset the state of the machine back to just the module contents.
891 void purgeFunction();
892
893 /// MDNode map iterators.
894 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
895
896 mdn_iterator mdn_begin() { return mdnMap.begin(); }
897 mdn_iterator mdn_end() { return mdnMap.end(); }
898 unsigned mdn_size() const { return mdnMap.size(); }
899 bool mdn_empty() const { return mdnMap.empty(); }
900
901 /// AttributeSet map iterators.
902 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
903
904 as_iterator as_begin() { return asMap.begin(); }
905 as_iterator as_end() { return asMap.end(); }
906 unsigned as_size() const { return asMap.size(); }
907 bool as_empty() const { return asMap.empty(); }
908
909 /// GUID map iterators.
910 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
911
912 /// These functions do the actual initialization.
913 inline void initializeIfNeeded();
914 int initializeIndexIfNeeded();
915
916 // Implementation Details
917private:
918 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
919 void CreateModuleSlot(const GlobalValue *V);
920
921 /// Record a metadata definition and the metadata nodes referenced by it.
922 void CreateMetadataSlot(const MDNode *N);
923
924 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
925 void CreateFunctionSlot(const Value *V);
926
927 /// Insert the specified AttributeSet into the slot table.
928 void CreateAttributeSetSlot(AttributeSet AS);
929
930 inline void CreateModulePathSlot(StringRef Path);
931 void CreateGUIDSlot(GlobalValue::GUID GUID);
932 void CreateTypeIdSlot(StringRef Id);
933 void CreateTypeIdCompatibleVtableSlot(StringRef Id);
934
935 /// Add all of the module level global variables (and their initializers)
936 /// and function declarations, but not the contents of those functions.
937 void processModule();
938 // Returns number of allocated slots
939 int processIndex();
940
941 /// Add all of the functions arguments, basic blocks, and instructions.
942 void processFunction();
943};
944
945ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
946 const Function *F)
947 : M(M), F(F), Machine(&Machine) {}
948
949ModuleSlotTracker::ModuleSlotTracker(const Module *M)
950 : ShouldCreateStorage(M), M(M) {}
951
952ModuleSlotTracker::~ModuleSlotTracker() = default;
953
954SlotTracker *ModuleSlotTracker::getMachine() {
955 if (!ShouldCreateStorage)
956 return Machine;
957
958 ShouldCreateStorage = false;
959 MachineStorage = std::make_unique<SlotTracker>(args&: M);
960 Machine = MachineStorage.get();
961 if (ProcessModuleHookFn)
962 Machine->setProcessHook(ProcessModuleHookFn);
963 if (ProcessFunctionHookFn)
964 Machine->setProcessHook(ProcessFunctionHookFn);
965 return Machine;
966}
967
968void ModuleSlotTracker::incorporateFunction(const Function &F) {
969 // Using getMachine() may lazily create the slot tracker.
970 if (!getMachine())
971 return;
972
973 // Nothing to do if this is the right function already.
974 if (this->F == &F)
975 return;
976 if (this->F)
977 Machine->purgeFunction();
978 Machine->incorporateFunction(F: &F);
979 this->F = &F;
980}
981
982int ModuleSlotTracker::getLocalSlot(const Value *V) {
983 assert(F && "No function incorporated");
984 return Machine->getLocalSlot(V);
985}
986
987void ModuleSlotTracker::setProcessHook(
988 std::function<void(AbstractSlotTrackerStorage *, const Module *)> Fn) {
989 ProcessModuleHookFn = std::move(Fn);
990}
991
992void ModuleSlotTracker::setProcessHook(
993 std::function<void(AbstractSlotTrackerStorage *, const Function *)> Fn) {
994 ProcessFunctionHookFn = std::move(Fn);
995}
996
997static SlotTracker *createSlotTracker(const Value *V) {
998 if (const auto *FA = dyn_cast<Argument>(Val: V))
999 return new SlotTracker(FA->getParent());
1000
1001 if (const auto *I = dyn_cast<Instruction>(Val: V))
1002 if (I->getParent())
1003 return new SlotTracker(I->getParent()->getParent());
1004
1005 if (const auto *BB = dyn_cast<BasicBlock>(Val: V))
1006 return new SlotTracker(BB->getParent());
1007
1008 if (const auto *GV = dyn_cast<GlobalVariable>(Val: V))
1009 return new SlotTracker(GV->getParent());
1010
1011 if (const auto *GA = dyn_cast<GlobalAlias>(Val: V))
1012 return new SlotTracker(GA->getParent());
1013
1014 if (const auto *GIF = dyn_cast<GlobalIFunc>(Val: V))
1015 return new SlotTracker(GIF->getParent());
1016
1017 if (const auto *Func = dyn_cast<Function>(Val: V))
1018 return new SlotTracker(Func);
1019
1020 return nullptr;
1021}
1022
1023#if 0
1024#define ST_DEBUG(X) dbgs() << X
1025#else
1026#define ST_DEBUG(X)
1027#endif
1028
1029// Module level constructor. Causes the contents of the Module (sans functions)
1030// to be added to the slot table.
1031SlotTracker::SlotTracker(const Module *M, bool ShouldTrackMetadataDefinitions)
1032 : TheModule(M),
1033 ShouldTrackMetadataDefinitions(ShouldTrackMetadataDefinitions) {}
1034
1035// Function level constructor. Causes the contents of the Module and the one
1036// function provided to be added to the slot table.
1037SlotTracker::SlotTracker(const Function *F)
1038 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
1039 ShouldTrackMetadataDefinitions(false) {}
1040
1041SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
1042 : TheModule(nullptr), ShouldTrackMetadataDefinitions(false),
1043 TheIndex(Index) {}
1044
1045inline void SlotTracker::initializeIfNeeded() {
1046 if (TheModule) {
1047 processModule();
1048 TheModule = nullptr; ///< Prevent re-processing next time we're called.
1049 }
1050
1051 if (TheFunction && !FunctionProcessed)
1052 processFunction();
1053}
1054
1055int SlotTracker::initializeIndexIfNeeded() {
1056 if (!TheIndex)
1057 return 0;
1058 int NumSlots = processIndex();
1059 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
1060 return NumSlots;
1061}
1062
1063// Iterate through all the global variables, functions, and global
1064// variable initializers and create slots for them.
1065void SlotTracker::processModule() {
1066 ST_DEBUG("begin processModule!\n");
1067
1068 // Add all of the unnamed global variables to the value table.
1069 for (const GlobalVariable &Var : TheModule->globals()) {
1070 if (!Var.hasName())
1071 CreateModuleSlot(V: &Var);
1072 auto Attrs = Var.getAttributes();
1073 if (Attrs.hasAttributes())
1074 CreateAttributeSetSlot(AS: Attrs);
1075 }
1076
1077 for (const GlobalAlias &A : TheModule->aliases()) {
1078 if (!A.hasName())
1079 CreateModuleSlot(V: &A);
1080 }
1081
1082 for (const GlobalIFunc &I : TheModule->ifuncs()) {
1083 if (!I.hasName())
1084 CreateModuleSlot(V: &I);
1085 }
1086
1087 for (const Function &F : *TheModule) {
1088 if (!F.hasName())
1089 // Add all the unnamed functions to the table.
1090 CreateModuleSlot(V: &F);
1091
1092 // Add all the function attributes to the table.
1093 // FIXME: Add attributes of other objects?
1094 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1095 if (FnAttrs.hasAttributes())
1096 CreateAttributeSetSlot(AS: FnAttrs);
1097 }
1098
1099 if (ProcessModuleHookFn)
1100 ProcessModuleHookFn(this, TheModule);
1101
1102 ST_DEBUG("end processModule!\n");
1103}
1104
1105// Process the arguments, basic blocks, and instructions of a function.
1106void SlotTracker::processFunction() {
1107 ST_DEBUG("begin processFunction!\n");
1108 fNext = 0;
1109
1110 // Add all the function arguments with no names.
1111 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1112 AE = TheFunction->arg_end(); AI != AE; ++AI)
1113 if (!AI->hasName())
1114 CreateFunctionSlot(V: &*AI);
1115
1116 ST_DEBUG("Inserting Instructions:\n");
1117
1118 // Add all of the basic blocks and instructions with no names.
1119 for (auto &BB : *TheFunction) {
1120 if (!BB.hasName())
1121 CreateFunctionSlot(V: &BB);
1122
1123 for (auto &I : BB) {
1124 if (!I.getType()->isVoidTy() && !I.hasName())
1125 CreateFunctionSlot(V: &I);
1126
1127 // We allow direct calls to any llvm.foo function here, because the
1128 // target may not be linked into the optimizer.
1129 if (const auto *Call = dyn_cast<CallBase>(Val: &I)) {
1130 // Add all the call attributes to the table.
1131 AttributeSet Attrs = Call->getAttributes().getFnAttrs();
1132 if (Attrs.hasAttributes())
1133 CreateAttributeSetSlot(AS: Attrs);
1134 }
1135 }
1136 }
1137
1138 if (ProcessFunctionHookFn)
1139 ProcessFunctionHookFn(this, TheFunction);
1140
1141 FunctionProcessed = true;
1142
1143 ST_DEBUG("end processFunction!\n");
1144}
1145
1146// Iterate through all the GUID in the index and create slots for them.
1147int SlotTracker::processIndex() {
1148 ST_DEBUG("begin processIndex!\n");
1149 assert(TheIndex);
1150
1151 // The first block of slots are just the module ids, which start at 0 and are
1152 // assigned consecutively. Since the StringMap iteration order isn't
1153 // guaranteed, order by path string before assigning slots.
1154 std::vector<StringRef> ModulePaths;
1155 for (auto &[ModPath, _] : TheIndex->modulePaths())
1156 ModulePaths.push_back(x: ModPath);
1157 llvm::sort(C&: ModulePaths);
1158 for (auto &ModPath : ModulePaths)
1159 CreateModulePathSlot(Path: ModPath);
1160
1161 // Start numbering the GUIDs after the module ids.
1162 GUIDNext = ModulePathNext;
1163
1164 // Sort by GUID for deterministic slot assignment.
1165 for (const auto &GlobalList : TheIndex->sortedGlobalValueSummariesRange())
1166 CreateGUIDSlot(GUID: GlobalList.first);
1167
1168 // Start numbering the TypeIdCompatibleVtables after the GUIDs.
1169 TypeIdCompatibleVtableNext = GUIDNext;
1170 for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1171 CreateTypeIdCompatibleVtableSlot(Id: TId.first);
1172
1173 // Start numbering the TypeIds after the TypeIdCompatibleVtables.
1174 TypeIdNext = TypeIdCompatibleVtableNext;
1175 for (const auto &TID : TheIndex->typeIds())
1176 CreateTypeIdSlot(Id: TID.second.first);
1177
1178 ST_DEBUG("end processIndex!\n");
1179 return TypeIdNext;
1180}
1181
1182namespace {
1183class MetadataNodeVisitor {
1184 /// Visited MDNodes.
1185 SmallPtrSet<const MDNode *, 32> VisitedMDNodes;
1186 function_ref<void(const MDNode *)> Visit;
1187
1188 void visit(const MDNode *N) {
1189 if (isa<DIExpression>(Val: N) || !VisitedMDNodes.insert(Ptr: N).second)
1190 return;
1191
1192 Visit(N);
1193 for (const MDOperand &Op : N->operands())
1194 if (const auto *OpNode = dyn_cast_or_null<MDNode>(Val: Op.get()))
1195 visit(N: OpNode);
1196 }
1197
1198 void visitGlobalObjectMetadata(const GlobalObject &GO) {
1199 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1200 GO.getAllMetadata(MDs);
1201 for (auto &MD : MDs)
1202 visit(N: MD.second);
1203 }
1204
1205 void visitDbgRecordMetadata(const DbgRecord &DR) {
1206 if (const auto *DVR = dyn_cast<const DbgVariableRecord>(Val: &DR)) {
1207 if (auto *Empty = dyn_cast_if_present<MDNode>(Val: DVR->getRawLocation()))
1208 visit(N: Empty);
1209 if (DVR->getRawVariable())
1210 visit(N: DVR->getRawVariable());
1211 if (DVR->isDbgAssign()) {
1212 if (auto *AssignID = DVR->getRawAssignID())
1213 visit(N: cast<MDNode>(Val: AssignID));
1214 if (auto *Empty = dyn_cast_if_present<MDNode>(Val: DVR->getRawAddress()))
1215 visit(N: Empty);
1216 }
1217 } else if (const auto *DLR = dyn_cast<const DbgLabelRecord>(Val: &DR)) {
1218 visit(N: DLR->getRawLabel());
1219 } else {
1220 llvm_unreachable("unsupported DbgRecord kind");
1221 }
1222 if (DR.getDebugLoc())
1223 visit(N: DR.getDebugLoc().getAsMDNode());
1224 }
1225
1226 void visitInstructionMetadata(const Instruction &I) {
1227 if (const auto *CI = dyn_cast<CallInst>(Val: &I))
1228 if (Function *F = CI->getCalledFunction())
1229 if (F->isIntrinsic())
1230 for (auto &Op : I.operands())
1231 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Val: Op))
1232 if (auto *N = dyn_cast<MDNode>(Val: V->getMetadata()))
1233 visit(N);
1234
1235 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1236 I.getAllMetadata(MDs);
1237 for (auto &MD : MDs)
1238 visit(N: MD.second);
1239 }
1240
1241 void visitFunctionMetadata(const Function &F) {
1242 visitGlobalObjectMetadata(GO: F);
1243 for (const BasicBlock &BB : F)
1244 for (const Instruction &I : BB) {
1245 for (const DbgRecord &DR : I.getDbgRecordRange())
1246 visitDbgRecordMetadata(DR);
1247 visitInstructionMetadata(I);
1248 }
1249 }
1250
1251public:
1252 MetadataNodeVisitor(function_ref<void(const MDNode *)> Visit)
1253 : Visit(Visit) {}
1254
1255 void visitModuleMetadata(const Module &M) {
1256 for (const GlobalVariable &Var : M.globals())
1257 visitGlobalObjectMetadata(GO: Var);
1258 for (const GlobalIFunc &I : M.ifuncs())
1259 visitGlobalObjectMetadata(GO: I);
1260 for (const NamedMDNode &NMD : M.named_metadata())
1261 for (const MDNode *N : NMD.operands())
1262 visit(N);
1263 for (const Function &F : M)
1264 visitFunctionMetadata(F);
1265 }
1266
1267 void visitMetadata(ArrayRef<const MDNode *> Metadata) {
1268 for (const MDNode *N : Metadata)
1269 visit(N);
1270 }
1271
1272 bool contains(const MDNode *N) const { return VisitedMDNodes.contains(Ptr: N); }
1273};
1274
1275class MetadataIDRenumberer {
1276 uint32_t NextID = 0;
1277
1278public:
1279 void run(const Module &M, ArrayRef<const MDNode *> AdditionalMetadata,
1280 ModuleSlotTracker::MachineMDNodeListType *AdditionalMetadataNodes =
1281 nullptr) {
1282 bool IsAdditionalMetadata = false;
1283 auto Renumber = [&](const MDNode *N) {
1284 N->getContext().pImpl->setMetadataPrintID(N: const_cast<MDNode *>(N),
1285 ID: NextID++);
1286 if (IsAdditionalMetadata && AdditionalMetadataNodes)
1287 AdditionalMetadataNodes->emplace_back(
1288 Args: N->getContext().pImpl->getMetadataPrintID(N), Args&: N);
1289 };
1290 MetadataNodeVisitor Visitor(Renumber);
1291
1292 Visitor.visitModuleMetadata(M);
1293
1294 IsAdditionalMetadata = true;
1295 Visitor.visitMetadata(Metadata: AdditionalMetadata);
1296
1297 // Keep IDs unique for nodes outside the canonical output.
1298 SmallVector<MDNode *, 32> RemainingNodes;
1299 M.getContext().pImpl->getAllMetadataNodes(Nodes&: RemainingNodes);
1300 llvm::erase_if(C&: RemainingNodes, P: [&](const MDNode *N) {
1301 return Visitor.contains(N) ||
1302 M.getContext().pImpl->getMetadataPrintID(N) >= NextID;
1303 });
1304 llvm::sort(C&: RemainingNodes, Comp: [&](const MDNode *LHS, const MDNode *RHS) {
1305 return M.getContext().pImpl->getMetadataPrintID(N: LHS) <
1306 M.getContext().pImpl->getMetadataPrintID(N: RHS);
1307 });
1308 for (MDNode *N : RemainingNodes)
1309 M.getContext().pImpl->setMetadataPrintID(
1310 N, ID: M.getContext().pImpl->allocateMetadataPrintID());
1311
1312 if (AdditionalMetadataNodes)
1313 llvm::sort(C&: *AdditionalMetadataNodes);
1314 }
1315};
1316} // namespace
1317
1318void Module::renumberMetadataForAssembly() {
1319 MetadataIDRenumberer().run(M: *this, AdditionalMetadata: {});
1320}
1321
1322void ModuleSlotTracker::renumberMetadataForAssembly(
1323 ArrayRef<const MDNode *> AdditionalMetadata,
1324 MachineMDNodeListType *AdditionalMetadataNodes) const {
1325 assert(M && "metadata renumbering requires a module");
1326 MetadataIDRenumberer().run(M: *M, AdditionalMetadata, AdditionalMetadataNodes);
1327}
1328
1329void ModuleSlotTracker::collectAdditionalMetadata(
1330 ArrayRef<const MDNode *> AdditionalMetadata,
1331 MachineMDNodeListType &AdditionalMetadataNodes) const {
1332 assert(M && "metadata collection requires a module");
1333 bool IsAdditionalMetadata = false;
1334 auto Collect = [&](const MDNode *N) {
1335 if (IsAdditionalMetadata)
1336 AdditionalMetadataNodes.emplace_back(
1337 Args: N->getContext().pImpl->getMetadataPrintID(N), Args&: N);
1338 };
1339 MetadataNodeVisitor Visitor(Collect);
1340 Visitor.visitModuleMetadata(M: *M);
1341 IsAdditionalMetadata = true;
1342 Visitor.visitMetadata(Metadata: AdditionalMetadata);
1343 llvm::sort(C&: AdditionalMetadataNodes);
1344}
1345
1346/// Clean up after incorporating a function. This is the only way to get out of
1347/// the function incorporation state that affects get*Slot/Create*Slot. Function
1348/// incorporation state is indicated by TheFunction != 0.
1349void SlotTracker::purgeFunction() {
1350 ST_DEBUG("begin purgeFunction!\n");
1351 fMap.clear(); // Simply discard the function level map
1352 TheFunction = nullptr;
1353 FunctionProcessed = false;
1354 ST_DEBUG("end purgeFunction!\n");
1355}
1356
1357/// getGlobalSlot - Get the slot number of a global value.
1358int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1359 // Check for uninitialized state and do lazy initialization.
1360 initializeIfNeeded();
1361
1362 // Find the value in the module map
1363 ValueMap::iterator MI = mMap.find(Val: V);
1364 return MI == mMap.end() ? -1 : (int)MI->second;
1365}
1366
1367void SlotTracker::setProcessHook(
1368 std::function<void(AbstractSlotTrackerStorage *, const Module *)> Fn) {
1369 ProcessModuleHookFn = std::move(Fn);
1370}
1371
1372void SlotTracker::setProcessHook(
1373 std::function<void(AbstractSlotTrackerStorage *, const Function *)> Fn) {
1374 ProcessFunctionHookFn = std::move(Fn);
1375}
1376
1377/// getMetadataSlot - Get the slot number of a MDNode.
1378void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1379
1380/// getMetadataSlot - Get the slot number of a MDNode.
1381int SlotTracker::getMetadataSlot(const MDNode *N) {
1382 // Check for uninitialized state and do lazy initialization.
1383 initializeIfNeeded();
1384
1385 if (isa<DIExpression>(Val: N))
1386 return -1;
1387 if (ShouldTrackMetadataDefinitions)
1388 CreateMetadataSlot(N);
1389 return N->getContext().pImpl->getMetadataPrintID(N);
1390}
1391
1392/// getLocalSlot - Get the slot number for a value that is local to a function.
1393int SlotTracker::getLocalSlot(const Value *V) {
1394 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1395
1396 // Check for uninitialized state and do lazy initialization.
1397 initializeIfNeeded();
1398
1399 ValueMap::iterator FI = fMap.find(Val: V);
1400 return FI == fMap.end() ? -1 : (int)FI->second;
1401}
1402
1403int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1404 // Check for uninitialized state and do lazy initialization.
1405 initializeIfNeeded();
1406
1407 // Find the AttributeSet in the module map.
1408 as_iterator AI = asMap.find(Val: AS);
1409 return AI == asMap.end() ? -1 : (int)AI->second;
1410}
1411
1412int SlotTracker::getModulePathSlot(StringRef Path) {
1413 // Check for uninitialized state and do lazy initialization.
1414 initializeIndexIfNeeded();
1415
1416 // Find the Module path in the map
1417 auto I = ModulePathMap.find(Key: Path);
1418 return I == ModulePathMap.end() ? -1 : (int)I->second;
1419}
1420
1421int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1422 // Check for uninitialized state and do lazy initialization.
1423 initializeIndexIfNeeded();
1424
1425 // Find the GUID in the map
1426 guid_iterator I = GUIDMap.find(Val: GUID);
1427 return I == GUIDMap.end() ? -1 : (int)I->second;
1428}
1429
1430int SlotTracker::getTypeIdSlot(StringRef Id) {
1431 // Check for uninitialized state and do lazy initialization.
1432 initializeIndexIfNeeded();
1433
1434 // Find the TypeId string in the map
1435 auto I = TypeIdMap.find(Key: Id);
1436 return I == TypeIdMap.end() ? -1 : (int)I->second;
1437}
1438
1439int SlotTracker::getTypeIdCompatibleVtableSlot(StringRef Id) {
1440 // Check for uninitialized state and do lazy initialization.
1441 initializeIndexIfNeeded();
1442
1443 // Find the TypeIdCompatibleVtable string in the map
1444 auto I = TypeIdCompatibleVtableMap.find(Key: Id);
1445 return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;
1446}
1447
1448/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1449void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1450 assert(V && "Can't insert a null Value into SlotTracker!");
1451 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1452 assert(!V->hasName() && "Doesn't need a slot!");
1453
1454 unsigned DestSlot = mNext++;
1455 mMap[V] = DestSlot;
1456
1457 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1458 DestSlot << " [");
1459 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1460 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1461 (isa<Function>(V) ? 'F' :
1462 (isa<GlobalAlias>(V) ? 'A' :
1463 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1464}
1465
1466/// CreateSlot - Create a new slot for the specified value if it has no name.
1467void SlotTracker::CreateFunctionSlot(const Value *V) {
1468 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1469
1470 unsigned DestSlot = fNext++;
1471 fMap[V] = DestSlot;
1472
1473 // G = Global, F = Function, o = other
1474 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1475 DestSlot << " [o]\n");
1476}
1477
1478/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1479void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1480 assert(N && "Can't insert a null Value into SlotTracker!");
1481
1482 if (isa<DIExpression>(Val: N))
1483 return;
1484
1485 unsigned ID = N->getContext().pImpl->getMetadataPrintID(N);
1486 if (!mdnMap.try_emplace(Key: N, Args&: ID).second)
1487 return;
1488
1489 for (const MDOperand &Op : N->operands())
1490 if (const auto *OpNode = dyn_cast_or_null<MDNode>(Val: Op.get()))
1491 CreateMetadataSlot(N: OpNode);
1492}
1493
1494void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1495 assert(AS.hasAttributes() && "Doesn't need a slot!");
1496
1497 if (asMap.try_emplace(Key: AS, Args&: asNext).second)
1498 ++asNext;
1499}
1500
1501/// Create a new slot for the specified Module
1502void SlotTracker::CreateModulePathSlot(StringRef Path) {
1503 ModulePathMap[Path] = ModulePathNext++;
1504}
1505
1506/// Create a new slot for the specified GUID
1507void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1508 GUIDMap[GUID] = GUIDNext++;
1509}
1510
1511/// Create a new slot for the specified Id
1512void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1513 TypeIdMap[Id] = TypeIdNext++;
1514}
1515
1516/// Create a new slot for the specified Id
1517void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {
1518 TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;
1519}
1520
1521namespace {
1522/// Common instances used by most of the printer functions.
1523struct AsmWriterContext {
1524 TypePrinting *TypePrinter = nullptr;
1525 SlotTracker *Machine = nullptr;
1526 const Module *Context = nullptr;
1527 const ModuleSlotTracker *MST = nullptr;
1528
1529 AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr,
1530 const ModuleSlotTracker *MST = nullptr)
1531 : TypePrinter(TP), Machine(ST), Context(M), MST(MST) {}
1532
1533 static AsmWriterContext &getEmpty() {
1534 static AsmWriterContext EmptyCtx(nullptr, nullptr);
1535 return EmptyCtx;
1536 }
1537
1538 /// A callback that will be triggered when the underlying printer
1539 /// prints a Metadata as operand.
1540 virtual void onWriteMetadataAsOperand(const Metadata *) {}
1541
1542 virtual ~AsmWriterContext() = default;
1543};
1544} // end anonymous namespace
1545
1546//===----------------------------------------------------------------------===//
1547// AsmWriter Implementation
1548//===----------------------------------------------------------------------===//
1549
1550static void writeAsOperandInternal(raw_ostream &Out, const Value *V,
1551 AsmWriterContext &WriterCtx,
1552 bool PrintType = false);
1553
1554static void writeAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1555 AsmWriterContext &WriterCtx,
1556 bool FromValue = false);
1557
1558static void writeOptimizationInfo(raw_ostream &Out, const User *U) {
1559 if (const auto *FPO = dyn_cast<const FPMathOperator>(Val: U))
1560 Out << FPO->getFastMathFlags();
1561
1562 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: U)) {
1563 if (OBO->hasNoUnsignedWrap())
1564 Out << " nuw";
1565 if (OBO->hasNoSignedWrap())
1566 Out << " nsw";
1567 } else if (const auto *Div = dyn_cast<PossiblyExactOperator>(Val: U)) {
1568 if (Div->isExact())
1569 Out << " exact";
1570 } else if (const auto *PDI = dyn_cast<PossiblyDisjointInst>(Val: U)) {
1571 if (PDI->isDisjoint())
1572 Out << " disjoint";
1573 } else if (const auto *GEP = dyn_cast<GEPOperator>(Val: U)) {
1574 if (GEP->isInBounds())
1575 Out << " inbounds";
1576 else if (GEP->hasNoUnsignedSignedWrap())
1577 Out << " nusw";
1578 if (GEP->hasNoUnsignedWrap())
1579 Out << " nuw";
1580 if (auto InRange = GEP->getInRange()) {
1581 Out << " inrange(" << InRange->getLower() << ", " << InRange->getUpper()
1582 << ")";
1583 }
1584 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(Val: U)) {
1585 if (NNI->hasNonNeg())
1586 Out << " nneg";
1587 } else if (const auto *TI = dyn_cast<TruncInst>(Val: U)) {
1588 if (TI->hasNoUnsignedWrap())
1589 Out << " nuw";
1590 if (TI->hasNoSignedWrap())
1591 Out << " nsw";
1592 } else if (const auto *ICmp = dyn_cast<ICmpInst>(Val: U)) {
1593 if (ICmp->hasSameSign())
1594 Out << " samesign";
1595 } else if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: U)) {
1596 if (ASC->hasNonNull())
1597 Out << " nonnull";
1598 }
1599}
1600
1601static void WriteFullHexAPInt(raw_ostream &Out, const APInt &Val) {
1602 SmallVector<char, 32> Bits;
1603 Val.toStringUnsigned(Str&: Bits, Radix: 16);
1604 unsigned NumDigits = std::max(a: (Val.getBitWidth() + 3) / 4, b: 1U);
1605 Out << "0x";
1606 for (unsigned i = 0; i < NumDigits - Bits.size(); i++)
1607 Out << '0';
1608 Out << Bits;
1609}
1610
1611static void writeAPFloatInternal(raw_ostream &Out, const APFloat &APF) {
1612 bool ForceBitwiseOutput = false;
1613 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1614 // ppc_fp128 types are double-double. The special cases set the second
1615 // (high) double to +0.0, so if the high word is nonzero, force the use of
1616 // bitwise output.
1617 APInt HiWord = APF.bitcastToAPInt().lshr(shiftAmt: 64);
1618 ForceBitwiseOutput = !HiWord.isZero();
1619 }
1620
1621 if (!ForceBitwiseOutput) {
1622 // Check for special values in APFloat.
1623 if (APF.isInfinity()) {
1624 Out << (APF.isNegative() ? '-' : '+') << "inf";
1625 return;
1626 }
1627
1628 if (APF.isNaN()) {
1629 Out << (APF.isNegative() ? '-' : '+');
1630 APInt Payload = APF.getNaNPayload();
1631 // The quiet bit of a NaN is the highest bit of the payload, so the
1632 // preferred QNaN value happens to be the sign mask value.
1633 if (Payload.isSignMask()) {
1634 Out << "qnan";
1635 } else {
1636 if (APF.isSignaling())
1637 Out << 's';
1638 Out << "nan(";
1639 // Clear out the signaling/quiet bit of the payload for output.
1640 Payload.clearBit(BitPosition: Payload.getBitWidth() - 1);
1641 // Trim the string to exclude leading 0's.
1642 WriteFullHexAPInt(Out, Val: Payload.trunc(width: Payload.getActiveBits()));
1643 Out << ')';
1644 }
1645 return;
1646 }
1647 }
1648
1649 // Try for a decimal string output. If the value is convertible back to the
1650 // same APFloat value, then we know that it is safe to use it. Otherwise, fall
1651 // back onto the hexadecimal format.
1652 SmallString<128> StrVal;
1653 APF.toString(Str&: StrVal, FormatPrecision: 6, FormatMaxPadding: 0, TruncateZero: false);
1654 if (APFloat(APF.getSemantics(), StrVal) == APF) {
1655 Out << StrVal;
1656 return;
1657 }
1658
1659 // Fallback to the hexadecimal format representing the bit string exactly.
1660 Out << 'f';
1661 APInt API = APF.bitcastToAPInt();
1662 WriteFullHexAPInt(Out, Val: API);
1663}
1664
1665static void writeConstantInternal(raw_ostream &Out, const Constant *CV,
1666 AsmWriterContext &WriterCtx) {
1667 if (const auto *CI = dyn_cast<ConstantInt>(Val: CV)) {
1668 Type *Ty = CI->getType();
1669
1670 if (Ty->isVectorTy()) {
1671 Out << "splat (";
1672 WriterCtx.TypePrinter->print(Ty: Ty->getScalarType(), OS&: Out);
1673 Out << " ";
1674 }
1675
1676 if (Ty->getScalarType()->isIntegerTy(BitWidth: 1))
1677 Out << (CI->getZExtValue() ? "true" : "false");
1678 else
1679 Out << CI->getValue();
1680
1681 if (Ty->isVectorTy())
1682 Out << ")";
1683
1684 return;
1685 }
1686
1687 if (const auto *CB = dyn_cast<ConstantByte>(Val: CV)) {
1688 Type *Ty = CB->getType();
1689
1690 if (Ty->isVectorTy()) {
1691 Out << "splat (";
1692 WriterCtx.TypePrinter->print(Ty: Ty->getScalarType(), OS&: Out);
1693 Out << " ";
1694 }
1695
1696 Out << CB->getValue();
1697
1698 if (Ty->isVectorTy())
1699 Out << ")";
1700
1701 return;
1702 }
1703
1704 if (const auto *CFP = dyn_cast<ConstantFP>(Val: CV)) {
1705 Type *Ty = CFP->getType();
1706
1707 if (Ty->isVectorTy()) {
1708 if (CFP->getValue().bitcastToAPInt().isZero()) {
1709 Out << "zeroinitializer";
1710 return;
1711 }
1712
1713 Out << "splat (";
1714 WriterCtx.TypePrinter->print(Ty: Ty->getScalarType(), OS&: Out);
1715 Out << " ";
1716 }
1717
1718 writeAPFloatInternal(Out, APF: CFP->getValueAPF());
1719
1720 if (Ty->isVectorTy())
1721 Out << ")";
1722
1723 return;
1724 }
1725
1726 if (isa<ConstantAggregateZero>(Val: CV) || isa<ConstantTargetNone>(Val: CV)) {
1727 Out << "zeroinitializer";
1728 return;
1729 }
1730
1731 if (const auto *BA = dyn_cast<BlockAddress>(Val: CV)) {
1732 Out << "blockaddress(";
1733 writeAsOperandInternal(Out, V: BA->getFunction(), WriterCtx);
1734 Out << ", ";
1735 writeAsOperandInternal(Out, V: BA->getBasicBlock(), WriterCtx);
1736 Out << ")";
1737 return;
1738 }
1739
1740 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: CV)) {
1741 Out << "dso_local_equivalent ";
1742 writeAsOperandInternal(Out, V: Equiv->getGlobalValue(), WriterCtx);
1743 return;
1744 }
1745
1746 if (const auto *NC = dyn_cast<NoCFIValue>(Val: CV)) {
1747 Out << "no_cfi ";
1748 writeAsOperandInternal(Out, V: NC->getGlobalValue(), WriterCtx);
1749 return;
1750 }
1751
1752 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(Val: CV)) {
1753 Out << "ptrauth (";
1754
1755 // ptrauth (ptr CST, i32 KEY[, i64 DISC[, ptr ADDRDISC[, ptr DS]?]?]?)
1756 unsigned NumOpsToWrite = 2;
1757 if (!CPA->getOperand(i_nocapture: 2)->isNullValue())
1758 NumOpsToWrite = 3;
1759 if (!isa<ConstantPointerNull>(Val: CPA->getOperand(i_nocapture: 3)))
1760 NumOpsToWrite = 4;
1761 if (!isa<ConstantPointerNull>(Val: CPA->getOperand(i_nocapture: 4)))
1762 NumOpsToWrite = 5;
1763
1764 ListSeparator LS;
1765 for (unsigned i = 0, e = NumOpsToWrite; i != e; ++i) {
1766 Out << LS;
1767 writeAsOperandInternal(Out, V: CPA->getOperand(i_nocapture: i), WriterCtx,
1768 /*PrintType=*/true);
1769 }
1770 Out << ')';
1771 return;
1772 }
1773
1774 if (const auto *CA = dyn_cast<ConstantArray>(Val: CV)) {
1775 Out << '[';
1776 ListSeparator LS;
1777 for (const Value *Op : CA->operands()) {
1778 Out << LS;
1779 writeAsOperandInternal(Out, V: Op, WriterCtx, /*PrintType=*/true);
1780 }
1781 Out << ']';
1782 return;
1783 }
1784
1785 if (const auto *CA = dyn_cast<ConstantDataArray>(Val: CV)) {
1786 // As a special case, print the array as a string if it is an array of
1787 // i8 with ConstantInt values.
1788 if (CA->isString()) {
1789 Out << "c\"";
1790 printEscapedString(Name: CA->getAsString(), Out);
1791 Out << '"';
1792 return;
1793 }
1794
1795 Out << '[';
1796 ListSeparator LS;
1797 for (uint64_t i = 0, e = CA->getNumElements(); i != e; ++i) {
1798 Out << LS;
1799 writeAsOperandInternal(Out, V: CA->getElementAsConstant(i), WriterCtx,
1800 /*PrintType=*/true);
1801 }
1802 Out << ']';
1803 return;
1804 }
1805
1806 if (const auto *CS = dyn_cast<ConstantStruct>(Val: CV)) {
1807 if (CS->getType()->isPacked())
1808 Out << '<';
1809 Out << '{';
1810 if (CS->getNumOperands() != 0) {
1811 Out << ' ';
1812 ListSeparator LS;
1813 for (const Value *Op : CS->operands()) {
1814 Out << LS;
1815 writeAsOperandInternal(Out, V: Op, WriterCtx, /*PrintType=*/true);
1816 }
1817 Out << ' ';
1818 }
1819 Out << '}';
1820 if (CS->getType()->isPacked())
1821 Out << '>';
1822 return;
1823 }
1824
1825 if (isa<ConstantVector>(Val: CV) || isa<ConstantDataVector>(Val: CV)) {
1826 auto *CVVTy = cast<FixedVectorType>(Val: CV->getType());
1827
1828 // Use the same shorthand for splat vector (i.e. "splat(Ty val)") as is
1829 // permitted on IR input to reduce the output changes when enabling
1830 // UseConstant{Int,FP}ForFixedLengthSplat.
1831 // TODO: Remove this block when the UseConstant{Int,FP}ForFixedLengthSplat
1832 // options are removed.
1833 if (auto *SplatVal = CV->getSplatValue()) {
1834 if (isa<ConstantInt>(Val: SplatVal) || isa<ConstantFP>(Val: SplatVal) ||
1835 isa<ConstantByte>(Val: SplatVal)) {
1836 Out << "splat (";
1837 writeAsOperandInternal(Out, V: SplatVal, WriterCtx, /*PrintType=*/true);
1838 Out << ')';
1839 return;
1840 }
1841 }
1842
1843 Out << '<';
1844 ListSeparator LS;
1845 for (unsigned i = 0, e = CVVTy->getNumElements(); i != e; ++i) {
1846 Out << LS;
1847 writeAsOperandInternal(Out, V: CV->getAggregateElement(Elt: i), WriterCtx,
1848 /*PrintType=*/true);
1849 }
1850 Out << '>';
1851 return;
1852 }
1853
1854 if (const auto *CPN = dyn_cast<ConstantPointerNull>(Val: CV)) {
1855 if (auto *VT = dyn_cast<VectorType>(Val: CPN->getType())) {
1856 Out << "splat (";
1857 writeAsOperandInternal(Out,
1858 V: ConstantPointerNull::get(T: VT->getElementType()),
1859 WriterCtx, /*PrintType=*/true);
1860 Out << ')';
1861 return;
1862 }
1863
1864 Out << "null";
1865 return;
1866 }
1867
1868 if (isa<ConstantTokenNone>(Val: CV)) {
1869 Out << "none";
1870 return;
1871 }
1872
1873 if (isa<PoisonValue>(Val: CV)) {
1874 Out << "poison";
1875 return;
1876 }
1877
1878 if (isa<UndefValue>(Val: CV)) {
1879 Out << "undef";
1880 return;
1881 }
1882
1883 if (const auto *CE = dyn_cast<ConstantExpr>(Val: CV)) {
1884 // Use the same shorthand for splat vector (i.e. "splat(Ty val)") as is
1885 // permitted on IR input to reduce the output changes when enabling
1886 // UseConstant{Int,FP}ForScalableSplat.
1887 // TODO: Remove this block when the UseConstant{Int,FP}ForScalableSplat
1888 // options are removed.
1889 if (CE->getOpcode() == Instruction::ShuffleVector) {
1890 if (auto *SplatVal = CE->getSplatValue()) {
1891 if (isa<ConstantInt>(Val: SplatVal) || isa<ConstantFP>(Val: SplatVal) ||
1892 isa<ConstantByte>(Val: SplatVal)) {
1893 Out << "splat (";
1894 writeAsOperandInternal(Out, V: SplatVal, WriterCtx, /*PrintType=*/true);
1895 Out << ')';
1896 return;
1897 }
1898 }
1899 }
1900
1901 Out << CE->getOpcodeName();
1902 writeOptimizationInfo(Out, U: CE);
1903 Out << " (";
1904
1905 if (const auto *GEP = dyn_cast<GEPOperator>(Val: CE)) {
1906 WriterCtx.TypePrinter->print(Ty: GEP->getSourceElementType(), OS&: Out);
1907 Out << ", ";
1908 }
1909
1910 ListSeparator LS;
1911 for (const Value *Op : CE->operands()) {
1912 Out << LS;
1913 writeAsOperandInternal(Out, V: Op, WriterCtx, /*PrintType=*/true);
1914 }
1915
1916 if (CE->isCast()) {
1917 Out << " to ";
1918 WriterCtx.TypePrinter->print(Ty: CE->getType(), OS&: Out);
1919 }
1920
1921 if (CE->getOpcode() == Instruction::ShuffleVector)
1922 printShuffleMask(Out, Ty: CE->getType(), Mask: CE->getShuffleMask());
1923
1924 Out << ')';
1925 return;
1926 }
1927
1928 Out << "<placeholder or erroneous Constant>";
1929}
1930
1931static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1932 AsmWriterContext &WriterCtx) {
1933 Out << "!{";
1934 ListSeparator LS;
1935 for (const Metadata *MD : Node->operands()) {
1936 Out << LS;
1937 if (!MD) {
1938 Out << "null";
1939 } else if (auto *MDV = dyn_cast<ValueAsMetadata>(Val: MD)) {
1940 Value *V = MDV->getValue();
1941 writeAsOperandInternal(Out, V, WriterCtx, /*PrintType=*/true);
1942 } else {
1943 writeAsOperandInternal(Out, MD, WriterCtx);
1944 WriterCtx.onWriteMetadataAsOperand(MD);
1945 }
1946 }
1947
1948 Out << "}";
1949}
1950
1951namespace {
1952
1953struct MDFieldPrinter {
1954 raw_ostream &Out;
1955 ListSeparator FS;
1956 AsmWriterContext &WriterCtx;
1957
1958 explicit MDFieldPrinter(raw_ostream &Out)
1959 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1960 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1961 : Out(Out), WriterCtx(Ctx) {}
1962
1963 void printTag(const DINode *N);
1964 void printMacinfoType(const DIMacroNode *N);
1965 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1966 void printString(StringRef Name, StringRef Value,
1967 bool ShouldSkipEmpty = true);
1968 void printMetadata(StringRef Name, const Metadata *MD,
1969 bool ShouldSkipNull = true);
1970 void printMetadataOrInt(StringRef Name, const Metadata *MD, bool IsUnsigned,
1971 bool ShouldSkipZero = true);
1972 template <class IntTy>
1973 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1974 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1975 bool ShouldSkipZero);
1976 void printBool(StringRef Name, bool Value,
1977 std::optional<bool> Default = std::nullopt);
1978 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1979 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1980 template <class IntTy, class Stringifier>
1981 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1982 bool ShouldSkipZero = true);
1983 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1984 void printNameTableKind(StringRef Name,
1985 DICompileUnit::DebugNameTableKind NTK);
1986 void printFixedPointKind(StringRef Name, DIFixedPointType::FixedPointKind V);
1987};
1988
1989} // end anonymous namespace
1990
1991void MDFieldPrinter::printTag(const DINode *N) {
1992 Out << FS << "tag: ";
1993 auto Tag = dwarf::TagString(Tag: N->getTag());
1994 if (!Tag.empty())
1995 Out << Tag;
1996 else
1997 Out << N->getTag();
1998}
1999
2000void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
2001 Out << FS << "type: ";
2002 auto Type = dwarf::MacinfoString(Encoding: N->getMacinfoType());
2003 if (!Type.empty())
2004 Out << Type;
2005 else
2006 Out << N->getMacinfoType();
2007}
2008
2009void MDFieldPrinter::printChecksum(
2010 const DIFile::ChecksumInfo<StringRef> &Checksum) {
2011 Out << FS << "checksumkind: " << Checksum.getKindAsString();
2012 printString(Name: "checksum", Value: Checksum.Value, /* ShouldSkipEmpty */ false);
2013}
2014
2015void MDFieldPrinter::printString(StringRef Name, StringRef Value,
2016 bool ShouldSkipEmpty) {
2017 if (ShouldSkipEmpty && Value.empty())
2018 return;
2019
2020 Out << FS << Name << ": \"";
2021 printEscapedString(Name: Value, Out);
2022 Out << "\"";
2023}
2024
2025static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
2026 AsmWriterContext &WriterCtx) {
2027 if (!MD) {
2028 Out << "null";
2029 return;
2030 }
2031 writeAsOperandInternal(Out, MD, WriterCtx);
2032 WriterCtx.onWriteMetadataAsOperand(MD);
2033}
2034
2035void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
2036 bool ShouldSkipNull) {
2037 if (ShouldSkipNull && !MD)
2038 return;
2039
2040 Out << FS << Name << ": ";
2041 writeMetadataAsOperand(Out, MD, WriterCtx);
2042}
2043
2044void MDFieldPrinter::printMetadataOrInt(StringRef Name, const Metadata *MD,
2045 bool IsUnsigned, bool ShouldSkipZero) {
2046 if (!MD)
2047 return;
2048
2049 if (auto *CI = dyn_cast<ConstantAsMetadata>(Val: MD)) {
2050 auto *CV = cast<ConstantInt>(Val: CI->getValue());
2051 if (IsUnsigned)
2052 printInt(Name, Int: CV->getZExtValue(), ShouldSkipZero);
2053 else
2054 printInt(Name, Int: CV->getSExtValue(), ShouldSkipZero);
2055 } else
2056 printMetadata(Name, MD);
2057}
2058
2059template <class IntTy>
2060void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
2061 if (ShouldSkipZero && !Int)
2062 return;
2063
2064 Out << FS << Name << ": " << Int;
2065}
2066
2067void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
2068 bool IsUnsigned, bool ShouldSkipZero) {
2069 if (ShouldSkipZero && Int.isZero())
2070 return;
2071
2072 Out << FS << Name << ": ";
2073 Int.print(OS&: Out, isSigned: !IsUnsigned);
2074}
2075
2076void MDFieldPrinter::printBool(StringRef Name, bool Value,
2077 std::optional<bool> Default) {
2078 if (Default && Value == *Default)
2079 return;
2080 Out << FS << Name << ": " << (Value ? "true" : "false");
2081}
2082
2083void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
2084 if (!Flags)
2085 return;
2086
2087 Out << FS << Name << ": ";
2088
2089 SmallVector<DINode::DIFlags, 8> SplitFlags;
2090 auto Extra = DINode::splitFlags(Flags, SplitFlags);
2091
2092 ListSeparator FlagsFS(" | ");
2093 for (auto F : SplitFlags) {
2094 auto StringF = DINode::getFlagString(Flag: F);
2095 assert(!StringF.empty() && "Expected valid flag");
2096 Out << FlagsFS << StringF;
2097 }
2098 if (Extra || SplitFlags.empty())
2099 Out << FlagsFS << Extra;
2100}
2101
2102void MDFieldPrinter::printDISPFlags(StringRef Name,
2103 DISubprogram::DISPFlags Flags) {
2104 // Always print this field, because no flags in the IR at all will be
2105 // interpreted as old-style isDefinition: true.
2106 Out << FS << Name << ": ";
2107
2108 if (!Flags) {
2109 Out << 0;
2110 return;
2111 }
2112
2113 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
2114 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
2115
2116 ListSeparator FlagsFS(" | ");
2117 for (auto F : SplitFlags) {
2118 auto StringF = DISubprogram::getFlagString(Flag: F);
2119 assert(!StringF.empty() && "Expected valid flag");
2120 Out << FlagsFS << StringF;
2121 }
2122 if (Extra || SplitFlags.empty())
2123 Out << FlagsFS << Extra;
2124}
2125
2126void MDFieldPrinter::printEmissionKind(StringRef Name,
2127 DICompileUnit::DebugEmissionKind EK) {
2128 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
2129}
2130
2131void MDFieldPrinter::printNameTableKind(StringRef Name,
2132 DICompileUnit::DebugNameTableKind NTK) {
2133 if (NTK == DICompileUnit::DebugNameTableKind::Default)
2134 return;
2135 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(PK: NTK);
2136}
2137
2138void MDFieldPrinter::printFixedPointKind(StringRef Name,
2139 DIFixedPointType::FixedPointKind V) {
2140 Out << FS << Name << ": " << DIFixedPointType::fixedPointKindString(V);
2141}
2142
2143template <class IntTy, class Stringifier>
2144void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
2145 Stringifier toString, bool ShouldSkipZero) {
2146 if (ShouldSkipZero && !Value)
2147 return;
2148
2149 Out << FS << Name << ": ";
2150 auto S = toString(Value);
2151 if (!S.empty())
2152 Out << S;
2153 else
2154 Out << Value;
2155}
2156
2157static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
2158 AsmWriterContext &WriterCtx) {
2159 Out << "!GenericDINode(";
2160 MDFieldPrinter Printer(Out, WriterCtx);
2161 Printer.printTag(N);
2162 Printer.printString(Name: "header", Value: N->getHeader());
2163 if (N->getNumDwarfOperands()) {
2164 Out << Printer.FS << "operands: {";
2165 ListSeparator IFS;
2166 for (auto &I : N->dwarf_operands()) {
2167 Out << IFS;
2168 writeMetadataAsOperand(Out, MD: I, WriterCtx);
2169 }
2170 Out << "}";
2171 }
2172 Out << ")";
2173}
2174
2175static void writeDILocation(raw_ostream &Out, const DILocation *DL,
2176 AsmWriterContext &WriterCtx) {
2177 Out << "!DILocation(";
2178 MDFieldPrinter Printer(Out, WriterCtx);
2179 // Always output the line, since 0 is a relevant and important value for it.
2180 Printer.printInt(Name: "line", Int: DL->getLine(), /* ShouldSkipZero */ false);
2181 Printer.printInt(Name: "column", Int: DL->getColumn());
2182 Printer.printMetadata(Name: "scope", MD: DL->getRawScope(), /* ShouldSkipNull */ false);
2183 Printer.printMetadata(Name: "inlinedAt", MD: DL->getRawInlinedAt());
2184 Printer.printBool(Name: "isImplicitCode", Value: DL->isImplicitCode(),
2185 /* Default */ false);
2186 Printer.printInt(Name: "atomGroup", Int: DL->getAtomGroup());
2187 Printer.printInt<unsigned>(Name: "atomRank", Int: DL->getAtomRank());
2188 Printer.printMetadata(Name: "irlayers", MD: DL->getRawIRLayers());
2189 Out << ")";
2190}
2191
2192static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N,
2193 AsmWriterContext &WriterCtx) {
2194 Out << "!DILayerLoc(";
2195 MDFieldPrinter Printer(Out, WriterCtx);
2196 Printer.printInt(Name: "line", Int: N->getLine(), /* ShouldSkipZero */ false);
2197 Printer.printInt(Name: "column", Int: N->getColumn());
2198 Printer.printMetadata(Name: "file", MD: N->getRawFile(), /* ShouldSkipNull */ false);
2199 Printer.printString(Name: "kind", Value: N->getKind(), /* ShouldSkipEmpty */ false);
2200 Out << ")";
2201}
2202
2203static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N,
2204 AsmWriterContext &WriterCtx) {
2205 Out << "!DILayerLocList(";
2206 ListSeparator FS;
2207 for (const MDOperand &Op : N->operands()) {
2208 Out << FS;
2209 writeMetadataAsOperand(Out, MD: Op, WriterCtx);
2210 }
2211 Out << ")";
2212}
2213
2214static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
2215 AsmWriterContext &WriterCtx) {
2216 Out << "!DIAssignID()";
2217 MDFieldPrinter Printer(Out, WriterCtx);
2218}
2219
2220static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
2221 AsmWriterContext &WriterCtx) {
2222 Out << "!DISubrange(";
2223 MDFieldPrinter Printer(Out, WriterCtx);
2224
2225 Printer.printMetadataOrInt(Name: "count", MD: N->getRawCountNode(),
2226 /* IsUnsigned */ false,
2227 /* ShouldSkipZero */ false);
2228
2229 // A lowerBound of constant 0 should not be skipped, since it is different
2230 // from an unspecified lower bound (= nullptr).
2231 Printer.printMetadataOrInt(Name: "lowerBound", MD: N->getRawLowerBound(),
2232 /* IsUnsigned */ false,
2233 /* ShouldSkipZero */ false);
2234 Printer.printMetadataOrInt(Name: "upperBound", MD: N->getRawUpperBound(),
2235 /* IsUnsigned */ false,
2236 /* ShouldSkipZero */ false);
2237 Printer.printMetadataOrInt(Name: "stride", MD: N->getRawStride(),
2238 /* IsUnsigned */ false,
2239 /* ShouldSkipZero */ false);
2240
2241 Out << ")";
2242}
2243
2244static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
2245 AsmWriterContext &WriterCtx) {
2246 Out << "!DIGenericSubrange(";
2247 MDFieldPrinter Printer(Out, WriterCtx);
2248
2249 auto GetConstant = [&](Metadata *Bound) -> std::optional<int64_t> {
2250 auto *BE = dyn_cast_or_null<DIExpression>(Val: Bound);
2251 if (!BE)
2252 return std::nullopt;
2253 if (BE->isConstant() &&
2254 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
2255 *BE->isConstant()) {
2256 return static_cast<int64_t>(BE->getElement(I: 1));
2257 }
2258 return std::nullopt;
2259 };
2260
2261 auto *Count = N->getRawCountNode();
2262 if (auto ConstantCount = GetConstant(Count))
2263 Printer.printInt(Name: "count", Int: *ConstantCount,
2264 /* ShouldSkipZero */ false);
2265 else
2266 Printer.printMetadata(Name: "count", MD: Count, /*ShouldSkipNull */ true);
2267
2268 auto *LBound = N->getRawLowerBound();
2269 if (auto ConstantLBound = GetConstant(LBound))
2270 Printer.printInt(Name: "lowerBound", Int: *ConstantLBound,
2271 /* ShouldSkipZero */ false);
2272 else
2273 Printer.printMetadata(Name: "lowerBound", MD: LBound, /*ShouldSkipNull */ true);
2274
2275 auto *UBound = N->getRawUpperBound();
2276 if (auto ConstantUBound = GetConstant(UBound))
2277 Printer.printInt(Name: "upperBound", Int: *ConstantUBound,
2278 /* ShouldSkipZero */ false);
2279 else
2280 Printer.printMetadata(Name: "upperBound", MD: UBound, /*ShouldSkipNull */ true);
2281
2282 auto *Stride = N->getRawStride();
2283 if (auto ConstantStride = GetConstant(Stride))
2284 Printer.printInt(Name: "stride", Int: *ConstantStride,
2285 /* ShouldSkipZero */ false);
2286 else
2287 Printer.printMetadata(Name: "stride", MD: Stride, /*ShouldSkipNull */ true);
2288
2289 Out << ")";
2290}
2291
2292static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
2293 AsmWriterContext &) {
2294 Out << "!DIEnumerator(";
2295 MDFieldPrinter Printer(Out);
2296 Printer.printString(Name: "name", Value: N->getName(), /* ShouldSkipEmpty */ false);
2297 Printer.printAPInt(Name: "value", Int: N->getValue(), IsUnsigned: N->isUnsigned(),
2298 /*ShouldSkipZero=*/false);
2299 if (N->isUnsigned())
2300 Printer.printBool(Name: "isUnsigned", Value: true);
2301 Out << ")";
2302}
2303
2304static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
2305 AsmWriterContext &WriterCtx) {
2306 Out << "!DIBasicType(";
2307 MDFieldPrinter Printer(Out, WriterCtx);
2308 if (N->getTag() != dwarf::DW_TAG_base_type)
2309 Printer.printTag(N);
2310 Printer.printString(Name: "name", Value: N->getName());
2311 Printer.printMetadata(Name: "scope", MD: N->getRawScope());
2312 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2313 Printer.printInt(Name: "line", Int: N->getLine());
2314 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2315 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2316 Printer.printInt(Name: "dataSize", Int: N->getDataSizeInBits());
2317 Printer.printDwarfEnum(Name: "encoding", Value: N->getEncoding(),
2318 toString: dwarf::AttributeEncodingString);
2319 Printer.printInt(Name: "num_extra_inhabitants", Int: N->getNumExtraInhabitants());
2320 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2321 Out << ")";
2322}
2323
2324static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N,
2325 AsmWriterContext &WriterCtx) {
2326 Out << "!DIFixedPointType(";
2327 MDFieldPrinter Printer(Out, WriterCtx);
2328 if (N->getTag() != dwarf::DW_TAG_base_type)
2329 Printer.printTag(N);
2330 Printer.printString(Name: "name", Value: N->getName());
2331 Printer.printMetadata(Name: "scope", MD: N->getRawScope());
2332 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2333 Printer.printInt(Name: "line", Int: N->getLine());
2334 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2335 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2336 Printer.printDwarfEnum(Name: "encoding", Value: N->getEncoding(),
2337 toString: dwarf::AttributeEncodingString);
2338 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2339 Printer.printFixedPointKind(Name: "kind", V: N->getKind());
2340 if (N->isRational()) {
2341 bool IsUnsigned = !N->isSigned();
2342 Printer.printAPInt(Name: "numerator", Int: N->getNumerator(), IsUnsigned, ShouldSkipZero: false);
2343 Printer.printAPInt(Name: "denominator", Int: N->getDenominator(), IsUnsigned, ShouldSkipZero: false);
2344 } else {
2345 Printer.printInt(Name: "factor", Int: N->getFactor());
2346 }
2347 Out << ")";
2348}
2349
2350static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2351 AsmWriterContext &WriterCtx) {
2352 Out << "!DIStringType(";
2353 MDFieldPrinter Printer(Out, WriterCtx);
2354 if (N->getTag() != dwarf::DW_TAG_string_type)
2355 Printer.printTag(N);
2356 Printer.printString(Name: "name", Value: N->getName());
2357 Printer.printMetadata(Name: "stringLength", MD: N->getRawStringLength());
2358 Printer.printMetadata(Name: "stringLengthExpression", MD: N->getRawStringLengthExp());
2359 Printer.printMetadata(Name: "stringLocationExpression",
2360 MD: N->getRawStringLocationExp());
2361 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2362 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2363 Printer.printDwarfEnum(Name: "encoding", Value: N->getEncoding(),
2364 toString: dwarf::AttributeEncodingString);
2365 Printer.printMetadata(Name: "charType", MD: N->getRawCharType());
2366 Out << ")";
2367}
2368
2369static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2370 AsmWriterContext &WriterCtx) {
2371 Out << "!DIDerivedType(";
2372 MDFieldPrinter Printer(Out, WriterCtx);
2373 Printer.printTag(N);
2374 Printer.printString(Name: "name", Value: N->getName());
2375 Printer.printMetadata(Name: "scope", MD: N->getRawScope());
2376 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2377 Printer.printInt(Name: "line", Int: N->getLine());
2378 Printer.printMetadata(Name: "baseType", MD: N->getRawBaseType(),
2379 /* ShouldSkipNull */ false);
2380 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2381 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2382 Printer.printMetadataOrInt(Name: "offset", MD: N->getRawOffsetInBits(), IsUnsigned: true);
2383 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2384 Printer.printMetadata(Name: "extraData", MD: N->getRawExtraData());
2385 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2386 Printer.printInt(Name: "dwarfAddressSpace", Int: *DWARFAddressSpace,
2387 /* ShouldSkipZero */ false);
2388 Printer.printMetadata(Name: "annotations", MD: N->getRawAnnotations());
2389 if (auto PtrAuthData = N->getPtrAuthData()) {
2390 Printer.printInt(Name: "ptrAuthKey", Int: PtrAuthData->key());
2391 Printer.printBool(Name: "ptrAuthIsAddressDiscriminated",
2392 Value: PtrAuthData->isAddressDiscriminated());
2393 Printer.printInt(Name: "ptrAuthExtraDiscriminator",
2394 Int: PtrAuthData->extraDiscriminator());
2395 Printer.printBool(Name: "ptrAuthIsaPointer", Value: PtrAuthData->isaPointer());
2396 Printer.printBool(Name: "ptrAuthAuthenticatesNullValues",
2397 Value: PtrAuthData->authenticatesNullValues());
2398 }
2399 Out << ")";
2400}
2401
2402static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N,
2403 AsmWriterContext &WriterCtx) {
2404 Out << "!DISubrangeType(";
2405 MDFieldPrinter Printer(Out, WriterCtx);
2406 Printer.printString(Name: "name", Value: N->getName());
2407 Printer.printMetadata(Name: "scope", MD: N->getRawScope());
2408 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2409 Printer.printInt(Name: "line", Int: N->getLine());
2410 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2411 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2412 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2413 Printer.printMetadata(Name: "baseType", MD: N->getRawBaseType(),
2414 /* ShouldSkipNull */ false);
2415 Printer.printMetadata(Name: "lowerBound", MD: N->getRawLowerBound());
2416 Printer.printMetadata(Name: "upperBound", MD: N->getRawUpperBound());
2417 Printer.printMetadata(Name: "stride", MD: N->getRawStride());
2418 Printer.printMetadata(Name: "bias", MD: N->getRawBias());
2419 Out << ")";
2420}
2421
2422static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2423 AsmWriterContext &WriterCtx) {
2424 Out << "!DICompositeType(";
2425 MDFieldPrinter Printer(Out, WriterCtx);
2426 Printer.printTag(N);
2427 Printer.printString(Name: "name", Value: N->getName());
2428 Printer.printMetadata(Name: "scope", MD: N->getRawScope());
2429 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2430 Printer.printInt(Name: "line", Int: N->getLine());
2431 Printer.printMetadata(Name: "baseType", MD: N->getRawBaseType());
2432 Printer.printMetadataOrInt(Name: "size", MD: N->getRawSizeInBits(), IsUnsigned: true);
2433 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2434 Printer.printMetadataOrInt(Name: "offset", MD: N->getRawOffsetInBits(), IsUnsigned: true);
2435 Printer.printInt(Name: "num_extra_inhabitants", Int: N->getNumExtraInhabitants());
2436 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2437 Printer.printMetadata(Name: "elements", MD: N->getRawElements());
2438 Printer.printDwarfEnum(Name: "runtimeLang", Value: N->getRuntimeLang(),
2439 toString: dwarf::LanguageString);
2440 Printer.printMetadata(Name: "vtableHolder", MD: N->getRawVTableHolder());
2441 Printer.printMetadata(Name: "templateParams", MD: N->getRawTemplateParams());
2442 Printer.printString(Name: "identifier", Value: N->getIdentifier());
2443 Printer.printMetadata(Name: "discriminator", MD: N->getRawDiscriminator());
2444 Printer.printMetadata(Name: "dataLocation", MD: N->getRawDataLocation());
2445 Printer.printMetadata(Name: "associated", MD: N->getRawAssociated());
2446 Printer.printMetadata(Name: "allocated", MD: N->getRawAllocated());
2447 if (auto *RankConst = N->getRankConst())
2448 Printer.printInt(Name: "rank", Int: RankConst->getSExtValue(),
2449 /* ShouldSkipZero */ false);
2450 else
2451 Printer.printMetadata(Name: "rank", MD: N->getRawRank(), /*ShouldSkipNull */ true);
2452 Printer.printMetadata(Name: "annotations", MD: N->getRawAnnotations());
2453 if (auto *Specification = N->getRawSpecification())
2454 Printer.printMetadata(Name: "specification", MD: Specification);
2455
2456 if (auto EnumKind = N->getEnumKind())
2457 Printer.printDwarfEnum(Name: "enumKind", Value: *EnumKind, toString: dwarf::EnumKindString,
2458 /*ShouldSkipZero=*/false);
2459
2460 Printer.printMetadata(Name: "bitStride", MD: N->getRawBitStride());
2461 Out << ")";
2462}
2463
2464static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2465 AsmWriterContext &WriterCtx) {
2466 Out << "!DISubroutineType(";
2467 MDFieldPrinter Printer(Out, WriterCtx);
2468 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2469 Printer.printDwarfEnum(Name: "cc", Value: N->getCC(), toString: dwarf::ConventionString);
2470 Printer.printMetadata(Name: "types", MD: N->getRawTypeArray(),
2471 /* ShouldSkipNull */ false);
2472 Out << ")";
2473}
2474
2475static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2476 Out << "!DIFile(";
2477 MDFieldPrinter Printer(Out);
2478 Printer.printString(Name: "filename", Value: N->getFilename(),
2479 /* ShouldSkipEmpty */ false);
2480 Printer.printString(Name: "directory", Value: N->getDirectory(),
2481 /* ShouldSkipEmpty */ false);
2482 // Print all values for checksum together, or not at all.
2483 if (N->getChecksum())
2484 Printer.printChecksum(Checksum: *N->getChecksum());
2485 if (N->getSource())
2486 Printer.printString(Name: "source", Value: *N->getSource(),
2487 /* ShouldSkipEmpty */ false);
2488 Out << ")";
2489}
2490
2491static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2492 AsmWriterContext &WriterCtx) {
2493 Out << "!DICompileUnit(";
2494 MDFieldPrinter Printer(Out, WriterCtx);
2495
2496 DISourceLanguageName Lang = N->getSourceLanguage();
2497
2498 if (Lang.hasVersionedName()) {
2499 Printer.printDwarfEnum(
2500 Name: "sourceLanguageName",
2501 Value: static_cast<llvm::dwarf::SourceLanguageName>(Lang.getName()),
2502 toString: dwarf::SourceLanguageNameString,
2503 /* ShouldSkipZero */ false);
2504
2505 Printer.printInt(Name: "sourceLanguageVersion", Int: Lang.getVersion(),
2506 /*ShouldSkipZero=*/true);
2507 } else {
2508 Printer.printDwarfEnum(Name: "language", Value: Lang.getName(), toString: dwarf::LanguageString,
2509 /* ShouldSkipZero */ false);
2510 }
2511
2512 Printer.printMetadata(Name: "file", MD: N->getRawFile(), /* ShouldSkipNull */ false);
2513 Printer.printString(Name: "producer", Value: N->getProducer());
2514 Printer.printBool(Name: "isOptimized", Value: N->isOptimized());
2515 Printer.printString(Name: "flags", Value: N->getFlags());
2516 Printer.printInt(Name: "runtimeVersion", Int: N->getRuntimeVersion(),
2517 /* ShouldSkipZero */ false);
2518 Printer.printString(Name: "splitDebugFilename", Value: N->getSplitDebugFilename());
2519 Printer.printEmissionKind(Name: "emissionKind", EK: N->getEmissionKind());
2520 Printer.printMetadata(Name: "enums", MD: N->getRawEnumTypes());
2521 Printer.printMetadata(Name: "retainedTypes", MD: N->getRawRetainedTypes());
2522 Printer.printMetadata(Name: "globals", MD: N->getRawGlobalVariables());
2523 Printer.printMetadata(Name: "imports", MD: N->getRawImportedEntities());
2524 Printer.printMetadata(Name: "macros", MD: N->getRawMacros());
2525 Printer.printInt(Name: "dwoId", Int: N->getDWOId());
2526 Printer.printBool(Name: "splitDebugInlining", Value: N->getSplitDebugInlining(), Default: true);
2527 Printer.printBool(Name: "debugInfoForProfiling", Value: N->getDebugInfoForProfiling(),
2528 Default: false);
2529 Printer.printNameTableKind(Name: "nameTableKind", NTK: N->getNameTableKind());
2530 Printer.printBool(Name: "rangesBaseAddress", Value: N->getRangesBaseAddress(), Default: false);
2531 Printer.printString(Name: "sysroot", Value: N->getSysRoot());
2532 Printer.printString(Name: "sdk", Value: N->getSDK());
2533 Printer.printDwarfEnum(Name: "dialect", Value: Lang.getDialect(),
2534 toString: dwarf::LanguageDialectString);
2535 Out << ")";
2536}
2537
2538static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2539 AsmWriterContext &WriterCtx) {
2540 Out << "!DISubprogram(";
2541 MDFieldPrinter Printer(Out, WriterCtx);
2542 Printer.printString(Name: "name", Value: N->getName());
2543 Printer.printString(Name: "linkageName", Value: N->getLinkageName());
2544 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2545 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2546 Printer.printInt(Name: "line", Int: N->getLine());
2547 Printer.printMetadata(Name: "type", MD: N->getRawType());
2548 Printer.printInt(Name: "scopeLine", Int: N->getScopeLine());
2549 Printer.printMetadata(Name: "containingType", MD: N->getRawContainingType());
2550 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2551 N->getVirtualIndex() != 0)
2552 Printer.printInt(Name: "virtualIndex", Int: N->getVirtualIndex(), ShouldSkipZero: false);
2553 Printer.printInt(Name: "thisAdjustment", Int: N->getThisAdjustment());
2554 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2555 Printer.printDISPFlags(Name: "spFlags", Flags: N->getSPFlags());
2556 Printer.printMetadata(Name: "unit", MD: N->getRawUnit());
2557 Printer.printMetadata(Name: "templateParams", MD: N->getRawTemplateParams());
2558 Printer.printMetadata(Name: "declaration", MD: N->getRawDeclaration());
2559 Printer.printMetadata(Name: "retainedNodes", MD: N->getRawRetainedNodes());
2560 Printer.printMetadata(Name: "thrownTypes", MD: N->getRawThrownTypes());
2561 Printer.printMetadata(Name: "annotations", MD: N->getRawAnnotations());
2562 Printer.printString(Name: "targetFuncName", Value: N->getTargetFuncName());
2563 Printer.printBool(Name: "keyInstructions", Value: N->getKeyInstructionsEnabled(), Default: false);
2564 Out << ")";
2565}
2566
2567static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2568 AsmWriterContext &WriterCtx) {
2569 Out << "!DILexicalBlock(";
2570 MDFieldPrinter Printer(Out, WriterCtx);
2571 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2572 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2573 Printer.printInt(Name: "line", Int: N->getLine());
2574 Printer.printInt(Name: "column", Int: N->getColumn());
2575 Out << ")";
2576}
2577
2578static void writeDILexicalBlockFile(raw_ostream &Out,
2579 const DILexicalBlockFile *N,
2580 AsmWriterContext &WriterCtx) {
2581 Out << "!DILexicalBlockFile(";
2582 MDFieldPrinter Printer(Out, WriterCtx);
2583 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2584 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2585 Printer.printInt(Name: "discriminator", Int: N->getDiscriminator(),
2586 /* ShouldSkipZero */ false);
2587 Out << ")";
2588}
2589
2590static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2591 AsmWriterContext &WriterCtx) {
2592 Out << "!DINamespace(";
2593 MDFieldPrinter Printer(Out, WriterCtx);
2594 Printer.printString(Name: "name", Value: N->getName());
2595 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2596 Printer.printBool(Name: "exportSymbols", Value: N->getExportSymbols(), Default: false);
2597 Out << ")";
2598}
2599
2600static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2601 AsmWriterContext &WriterCtx) {
2602 Out << "!DICommonBlock(";
2603 MDFieldPrinter Printer(Out, WriterCtx);
2604 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), ShouldSkipNull: false);
2605 Printer.printMetadata(Name: "declaration", MD: N->getRawDecl(), ShouldSkipNull: false);
2606 Printer.printString(Name: "name", Value: N->getName());
2607 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2608 Printer.printInt(Name: "line", Int: N->getLineNo());
2609 Out << ")";
2610}
2611
2612static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2613 AsmWriterContext &WriterCtx) {
2614 Out << "!DIMacro(";
2615 MDFieldPrinter Printer(Out, WriterCtx);
2616 Printer.printMacinfoType(N);
2617 Printer.printInt(Name: "line", Int: N->getLine());
2618 Printer.printString(Name: "name", Value: N->getName());
2619 Printer.printString(Name: "value", Value: N->getValue());
2620 Out << ")";
2621}
2622
2623static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2624 AsmWriterContext &WriterCtx) {
2625 Out << "!DIMacroFile(";
2626 MDFieldPrinter Printer(Out, WriterCtx);
2627 Printer.printInt(Name: "line", Int: N->getLine());
2628 Printer.printMetadata(Name: "file", MD: N->getRawFile(), /* ShouldSkipNull */ false);
2629 Printer.printMetadata(Name: "nodes", MD: N->getRawElements());
2630 Out << ")";
2631}
2632
2633static void writeDIModule(raw_ostream &Out, const DIModule *N,
2634 AsmWriterContext &WriterCtx) {
2635 Out << "!DIModule(";
2636 MDFieldPrinter Printer(Out, WriterCtx);
2637 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2638 Printer.printString(Name: "name", Value: N->getName());
2639 Printer.printString(Name: "configMacros", Value: N->getConfigurationMacros());
2640 Printer.printString(Name: "includePath", Value: N->getIncludePath());
2641 Printer.printString(Name: "apinotes", Value: N->getAPINotesFile());
2642 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2643 Printer.printInt(Name: "line", Int: N->getLineNo());
2644 Printer.printBool(Name: "isDecl", Value: N->getIsDecl(), /* Default */ false);
2645 Out << ")";
2646}
2647
2648static void writeDITemplateTypeParameter(raw_ostream &Out,
2649 const DITemplateTypeParameter *N,
2650 AsmWriterContext &WriterCtx) {
2651 Out << "!DITemplateTypeParameter(";
2652 MDFieldPrinter Printer(Out, WriterCtx);
2653 Printer.printString(Name: "name", Value: N->getName());
2654 Printer.printMetadata(Name: "type", MD: N->getRawType(), /* ShouldSkipNull */ false);
2655 Printer.printBool(Name: "defaulted", Value: N->isDefault(), /* Default= */ false);
2656 Out << ")";
2657}
2658
2659static void writeDITemplateValueParameter(raw_ostream &Out,
2660 const DITemplateValueParameter *N,
2661 AsmWriterContext &WriterCtx) {
2662 Out << "!DITemplateValueParameter(";
2663 MDFieldPrinter Printer(Out, WriterCtx);
2664 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2665 Printer.printTag(N);
2666 Printer.printString(Name: "name", Value: N->getName());
2667 Printer.printMetadata(Name: "type", MD: N->getRawType());
2668 Printer.printBool(Name: "defaulted", Value: N->isDefault(), /* Default= */ false);
2669 Printer.printMetadata(Name: "value", MD: N->getValue(), /* ShouldSkipNull */ false);
2670 Out << ")";
2671}
2672
2673static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2674 AsmWriterContext &WriterCtx) {
2675 Out << "!DIGlobalVariable(";
2676 MDFieldPrinter Printer(Out, WriterCtx);
2677 Printer.printString(Name: "name", Value: N->getName());
2678 Printer.printString(Name: "linkageName", Value: N->getLinkageName());
2679 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2680 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2681 Printer.printInt(Name: "line", Int: N->getLine());
2682 Printer.printMetadata(Name: "type", MD: N->getRawType());
2683 Printer.printBool(Name: "isLocal", Value: N->isLocalToUnit());
2684 Printer.printBool(Name: "isDefinition", Value: N->isDefinition());
2685 Printer.printMetadata(Name: "declaration", MD: N->getRawStaticDataMemberDeclaration());
2686 Printer.printMetadata(Name: "templateParams", MD: N->getRawTemplateParams());
2687 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2688 Printer.printMetadata(Name: "annotations", MD: N->getRawAnnotations());
2689 Out << ")";
2690}
2691
2692static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2693 AsmWriterContext &WriterCtx) {
2694 Out << "!DILocalVariable(";
2695 MDFieldPrinter Printer(Out, WriterCtx);
2696 Printer.printString(Name: "name", Value: N->getName());
2697 Printer.printInt(Name: "arg", Int: N->getArg());
2698 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2699 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2700 Printer.printInt(Name: "line", Int: N->getLine());
2701 Printer.printMetadata(Name: "type", MD: N->getRawType());
2702 Printer.printDIFlags(Name: "flags", Flags: N->getFlags());
2703 Printer.printInt(Name: "align", Int: N->getAlignInBits());
2704 Printer.printMetadata(Name: "annotations", MD: N->getRawAnnotations());
2705 Out << ")";
2706}
2707
2708static void writeDILabel(raw_ostream &Out, const DILabel *N,
2709 AsmWriterContext &WriterCtx) {
2710 Out << "!DILabel(";
2711 MDFieldPrinter Printer(Out, WriterCtx);
2712 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2713 Printer.printString(Name: "name", Value: N->getName());
2714 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2715 Printer.printInt(Name: "line", Int: N->getLine(), /* ShouldSkipZero */ false);
2716 Printer.printInt(Name: "column", Int: N->getColumn());
2717 Printer.printBool(Name: "isArtificial", Value: N->isArtificial(), Default: false);
2718 if (N->getCoroSuspendIdx())
2719 Printer.printInt(Name: "coroSuspendIdx", Int: *N->getCoroSuspendIdx(),
2720 /* ShouldSkipZero */ false);
2721 Out << ")";
2722}
2723
2724static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2725 AsmWriterContext &WriterCtx) {
2726 Out << "!DIExpression(";
2727 ListSeparator FS;
2728 if (N->isValid()) {
2729 for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2730 auto OpStr = dwarf::OperationEncodingString(Encoding: Op.getOp());
2731 assert(!OpStr.empty() && "Expected valid opcode");
2732
2733 Out << FS << OpStr;
2734 if (auto Convert = dyn_cast<DIExpression::ConvertOp>(Val: Op)) {
2735 Out << FS << Convert.getBitSize();
2736 Out << FS << dwarf::AttributeEncodingString(Encoding: Convert.getEncoding());
2737 } else {
2738 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2739 Out << FS << Op.getArg(I: A);
2740 }
2741 }
2742 } else {
2743 for (const auto &I : N->getElements())
2744 Out << FS << I;
2745 }
2746 Out << ")";
2747}
2748
2749static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2750 AsmWriterContext &WriterCtx,
2751 bool FromValue = false) {
2752 assert(FromValue &&
2753 "Unexpected DIArgList metadata outside of value argument");
2754 Out << "!DIArgList(";
2755 ListSeparator FS;
2756 MDFieldPrinter Printer(Out, WriterCtx);
2757 for (const Metadata *Arg : N->getArgs()) {
2758 Out << FS;
2759 writeAsOperandInternal(Out, MD: Arg, WriterCtx, FromValue: true);
2760 }
2761 Out << ")";
2762}
2763
2764static void writeDIGlobalVariableExpression(raw_ostream &Out,
2765 const DIGlobalVariableExpression *N,
2766 AsmWriterContext &WriterCtx) {
2767 Out << "!DIGlobalVariableExpression(";
2768 MDFieldPrinter Printer(Out, WriterCtx);
2769 Printer.printMetadata(Name: "var", MD: N->getVariable());
2770 Printer.printMetadata(Name: "expr", MD: N->getExpression());
2771 Out << ")";
2772}
2773
2774static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2775 AsmWriterContext &WriterCtx) {
2776 Out << "!DIObjCProperty(";
2777 MDFieldPrinter Printer(Out, WriterCtx);
2778 Printer.printString(Name: "name", Value: N->getName());
2779 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2780 Printer.printInt(Name: "line", Int: N->getLine());
2781 Printer.printString(Name: "setter", Value: N->getSetterName());
2782 Printer.printString(Name: "getter", Value: N->getGetterName());
2783 Printer.printInt(Name: "attributes", Int: N->getAttributes());
2784 Printer.printMetadata(Name: "type", MD: N->getRawType());
2785 Out << ")";
2786}
2787
2788static void writeDIProperty(raw_ostream &Out, const DIProperty *N,
2789 AsmWriterContext &WriterCtx) {
2790 Out << "!DIProperty(";
2791 MDFieldPrinter Printer(Out, WriterCtx);
2792 Printer.printString(Name: "name", Value: N->getName());
2793 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2794 Printer.printInt(Name: "line", Int: N->getLine());
2795 Printer.printMetadata(Name: "type", MD: N->getRawType());
2796 Printer.printMetadata(Name: "backing_storage", MD: N->getRawBackingStorage());
2797 Out << ")";
2798}
2799
2800static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2801 AsmWriterContext &WriterCtx) {
2802 Out << "!DIImportedEntity(";
2803 MDFieldPrinter Printer(Out, WriterCtx);
2804 Printer.printTag(N);
2805 Printer.printString(Name: "name", Value: N->getName());
2806 Printer.printMetadata(Name: "scope", MD: N->getRawScope(), /* ShouldSkipNull */ false);
2807 Printer.printMetadata(Name: "entity", MD: N->getRawEntity());
2808 Printer.printMetadata(Name: "file", MD: N->getRawFile());
2809 Printer.printInt(Name: "line", Int: N->getLine());
2810 Printer.printMetadata(Name: "elements", MD: N->getRawElements());
2811 Out << ")";
2812}
2813
2814static void writeMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2815 AsmWriterContext &Ctx) {
2816 if (Node->isDistinct())
2817 Out << "distinct ";
2818 else if (Node->isTemporary())
2819 Out << "<temporary!> "; // Handle broken code.
2820
2821 switch (Node->getMetadataID()) {
2822 default:
2823 llvm_unreachable("Expected uniquable MDNode");
2824#define HANDLE_MDNODE_LEAF(CLASS) \
2825 case Metadata::CLASS##Kind: \
2826 write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2827 break;
2828#include "llvm/IR/Metadata.def"
2829 }
2830}
2831
2832// Full implementation of printing a Value as an operand with support for
2833// TypePrinting, etc.
2834static void writeAsOperandInternal(raw_ostream &Out, const Value *V,
2835 AsmWriterContext &WriterCtx,
2836 bool PrintType) {
2837 if (PrintType) {
2838 WriterCtx.TypePrinter->print(Ty: V->getType(), OS&: Out);
2839 Out << ' ';
2840 }
2841
2842 if (V->hasName()) {
2843 printLLVMName(OS&: Out, V);
2844 return;
2845 }
2846
2847 const auto *CV = dyn_cast<Constant>(Val: V);
2848 if (CV && !isa<GlobalValue>(Val: CV)) {
2849 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2850 writeConstantInternal(Out, CV, WriterCtx);
2851 return;
2852 }
2853
2854 if (const auto *IA = dyn_cast<InlineAsm>(Val: V)) {
2855 Out << "asm ";
2856 if (IA->hasSideEffects())
2857 Out << "sideeffect ";
2858 if (IA->isAlignStack())
2859 Out << "alignstack ";
2860 // We don't emit the AD_ATT dialect as it's the assumed default.
2861 if (IA->getDialect() == InlineAsm::AD_Intel)
2862 Out << "inteldialect ";
2863 if (IA->canThrow())
2864 Out << "unwind ";
2865 Out << '"';
2866 printEscapedString(Name: IA->getAsmString(), Out);
2867 Out << "\", \"";
2868 printEscapedString(Name: IA->getConstraintString(), Out);
2869 Out << '"';
2870 return;
2871 }
2872
2873 if (auto *MD = dyn_cast<MetadataAsValue>(Val: V)) {
2874 writeAsOperandInternal(Out, MD: MD->getMetadata(), WriterCtx,
2875 /* FromValue */ true);
2876 return;
2877 }
2878
2879 char Prefix = '%';
2880 int Slot;
2881 auto *Machine = WriterCtx.Machine;
2882 // If we have a SlotTracker, use it.
2883 if (Machine) {
2884 if (const auto *GV = dyn_cast<GlobalValue>(Val: V)) {
2885 Slot = Machine->getGlobalSlot(V: GV);
2886 Prefix = '@';
2887 } else {
2888 Slot = Machine->getLocalSlot(V);
2889
2890 // If the local value didn't succeed, then we may be referring to a value
2891 // from a different function. Translate it, as this can happen when using
2892 // address of blocks.
2893 if (Slot == -1)
2894 if ((Machine = createSlotTracker(V))) {
2895 Slot = Machine->getLocalSlot(V);
2896 delete Machine;
2897 }
2898 }
2899 } else if ((Machine = createSlotTracker(V))) {
2900 // Otherwise, create one to get the # and then destroy it.
2901 if (const auto *GV = dyn_cast<GlobalValue>(Val: V)) {
2902 Slot = Machine->getGlobalSlot(V: GV);
2903 Prefix = '@';
2904 } else {
2905 Slot = Machine->getLocalSlot(V);
2906 }
2907 delete Machine;
2908 Machine = nullptr;
2909 } else {
2910 Slot = -1;
2911 }
2912
2913 if (Slot != -1)
2914 Out << Prefix << Slot;
2915 else
2916 Out << "<badref>";
2917}
2918
2919static void writeAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2920 AsmWriterContext &WriterCtx,
2921 bool FromValue) {
2922 // Write DIExpressions and DIArgLists inline when used as a value. Improves
2923 // readability of debug info intrinsics.
2924 if (const auto *Expr = dyn_cast<DIExpression>(Val: MD)) {
2925 writeDIExpression(Out, N: Expr, WriterCtx);
2926 return;
2927 }
2928 if (const auto *ArgList = dyn_cast<DIArgList>(Val: MD)) {
2929 writeDIArgList(Out, N: ArgList, WriterCtx, FromValue);
2930 return;
2931 }
2932
2933 if (const auto *N = dyn_cast<MDNode>(Val: MD)) {
2934 if (const auto *Loc = dyn_cast<DILocation>(Val: N);
2935 Loc && WriterCtx.MST &&
2936 WriterCtx.MST->shouldPrintDebugLocationInline(Loc)) {
2937 writeDILocation(Out, DL: Loc, WriterCtx);
2938 return;
2939 }
2940
2941 std::unique_ptr<SlotTracker> MachineStorage;
2942 SaveAndRestore SARMachine(WriterCtx.Machine);
2943 if (!WriterCtx.Machine) {
2944 MachineStorage = std::make_unique<SlotTracker>(args&: WriterCtx.Context);
2945 WriterCtx.Machine = MachineStorage.get();
2946 }
2947 int Slot = WriterCtx.Machine->getMetadataSlot(N);
2948 if (Slot == -1) {
2949 if (const auto *Loc = dyn_cast<DILocation>(Val: N)) {
2950 writeDILocation(Out, DL: Loc, WriterCtx);
2951 return;
2952 }
2953 // Give the pointer value instead of "badref", since this comes up all
2954 // the time when debugging.
2955 Out << "<" << N << ">";
2956 } else
2957 Out << '!' << Slot;
2958 return;
2959 }
2960
2961 if (const auto *MDS = dyn_cast<MDString>(Val: MD)) {
2962 Out << "!\"";
2963 printEscapedString(Name: MDS->getString(), Out);
2964 Out << '"';
2965 return;
2966 }
2967
2968 auto *V = cast<ValueAsMetadata>(Val: MD);
2969 assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
2970 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2971 "Unexpected function-local metadata outside of value argument");
2972
2973 writeAsOperandInternal(Out, V: V->getValue(), WriterCtx, /*PrintType=*/true);
2974}
2975
2976namespace {
2977
2978class AssemblyWriter {
2979 formatted_raw_ostream &Out;
2980 const Module *TheModule = nullptr;
2981 const ModuleSummaryIndex *TheIndex = nullptr;
2982 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2983 SlotTracker &Machine;
2984 TypePrinting TypePrinter;
2985 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2986 bool IsForDebug;
2987 bool ShouldPreserveUseListOrder;
2988 UseListOrderMap UseListOrders;
2989 SmallVector<StringRef, 8> MDNames;
2990 /// Synchronization scope names registered with LLVMContext.
2991 SmallVector<StringRef, 8> SSNs;
2992 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2993
2994public:
2995 /// Construct an AssemblyWriter with an external SlotTracker
2996 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2997 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2998 bool ShouldPreserveUseListOrder = false);
2999
3000 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
3001 const ModuleSummaryIndex *Index, bool IsForDebug);
3002
3003 AsmWriterContext getContext() {
3004 return AsmWriterContext(&TypePrinter, &Machine, TheModule);
3005 }
3006
3007 void printMDNodeBody(const MDNode *MD);
3008 void printNamedMDNode(const NamedMDNode *NMD);
3009
3010 void printModule(const Module *M);
3011
3012 void writeOperand(const Value *Op, bool PrintType);
3013 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
3014 void writeOperandBundles(const CallBase *Call);
3015 void writeSyncScope(const LLVMContext &Context,
3016 SyncScope::ID SSID);
3017 void writeAtomic(const LLVMContext &Context,
3018 AtomicOrdering Ordering,
3019 SyncScope::ID SSID);
3020 void writeAtomicCmpXchg(const LLVMContext &Context,
3021 AtomicOrdering SuccessOrdering,
3022 AtomicOrdering FailureOrdering,
3023 SyncScope::ID SSID);
3024
3025 void writeAllMDNodes();
3026 void writeMDNode(unsigned Slot, const MDNode *Node);
3027 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
3028 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
3029 void writeAllAttributeGroups();
3030
3031 void printTypeIdentities();
3032 void printGlobal(const GlobalVariable *GV);
3033 void printAlias(const GlobalAlias *GA);
3034 void printIFunc(const GlobalIFunc *GI);
3035 void printComdat(const Comdat *C);
3036 void printFunction(const Function *F);
3037 void printArgument(const Argument *FA, AttributeSet Attrs);
3038 void printBasicBlock(const BasicBlock *BB);
3039 void printInstructionLine(const Instruction &I);
3040 void printInstruction(const Instruction &I);
3041 void printDbgMarker(const DbgMarker &DPI);
3042 void printDbgVariableRecord(const DbgVariableRecord &DVR);
3043 void printDbgLabelRecord(const DbgLabelRecord &DLR);
3044 void printDbgRecord(const DbgRecord &DR);
3045 void printDbgRecordLine(const DbgRecord &DR);
3046
3047 void printUseListOrder(const Value *V, ArrayRef<unsigned> Shuffle);
3048 void printUseLists(const Function *F);
3049
3050 void printModuleSummaryIndex();
3051 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
3052 void printSummary(const GlobalValueSummary &Summary);
3053 void printAliasSummary(const AliasSummary *AS);
3054 void printGlobalVarSummary(const GlobalVarSummary *GS);
3055 void printFunctionSummary(const FunctionSummary *FS);
3056 void printTypeIdSummary(const TypeIdSummary &TIS);
3057 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
3058 void printTypeTestResolution(const TypeTestResolution &TTRes);
3059 void printArgs(ArrayRef<uint64_t> Args);
3060 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
3061 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
3062 void printVFuncId(const FunctionSummary::VFuncId VFId);
3063 void printNonConstVCalls(ArrayRef<FunctionSummary::VFuncId> VCallList,
3064 const char *Tag);
3065 void printConstVCalls(ArrayRef<FunctionSummary::ConstVCall> VCallList,
3066 const char *Tag);
3067
3068private:
3069 /// Print out metadata attachments.
3070 void printMetadataAttachments(
3071 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3072 StringRef Separator);
3073
3074 // printInfoComment - Print a little comment after the instruction indicating
3075 // which slot it occupies.
3076 void printInfoComment(const Value &V, bool isMaterializable = false);
3077
3078 // printGCRelocateComment - print comment after call to the gc.relocate
3079 // intrinsic indicating base and derived pointer names.
3080 void printGCRelocateComment(const GCRelocateInst &Relocate);
3081};
3082
3083} // end anonymous namespace
3084
3085AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
3086 const Module *M, AssemblyAnnotationWriter *AAW,
3087 bool IsForDebug, bool ShouldPreserveUseListOrder)
3088 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
3089 IsForDebug(IsForDebug),
3090 ShouldPreserveUseListOrder(
3091 PreserveAssemblyUseListOrder.getNumOccurrences()
3092 ? PreserveAssemblyUseListOrder
3093 : ShouldPreserveUseListOrder) {}
3094
3095AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
3096 const ModuleSummaryIndex *Index, bool IsForDebug)
3097 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
3098 IsForDebug(IsForDebug),
3099 ShouldPreserveUseListOrder(PreserveAssemblyUseListOrder) {}
3100
3101void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
3102 if (!Operand) {
3103 Out << "<null operand!>";
3104 return;
3105 }
3106 auto WriteCtx = getContext();
3107 writeAsOperandInternal(Out, V: Operand, WriterCtx&: WriteCtx, PrintType);
3108}
3109
3110void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
3111 SyncScope::ID SSID) {
3112 switch (SSID) {
3113 case SyncScope::System: {
3114 break;
3115 }
3116 default: {
3117 if (SSNs.empty())
3118 Context.getSyncScopeNames(SSNs);
3119
3120 Out << " syncscope(\"";
3121 printEscapedString(Name: SSNs[SSID], Out);
3122 Out << "\")";
3123 break;
3124 }
3125 }
3126}
3127
3128void AssemblyWriter::writeAtomic(const LLVMContext &Context,
3129 AtomicOrdering Ordering,
3130 SyncScope::ID SSID) {
3131 if (Ordering == AtomicOrdering::NotAtomic)
3132 return;
3133
3134 writeSyncScope(Context, SSID);
3135 Out << " " << toIRString(ao: Ordering);
3136}
3137
3138void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
3139 AtomicOrdering SuccessOrdering,
3140 AtomicOrdering FailureOrdering,
3141 SyncScope::ID SSID) {
3142 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
3143 FailureOrdering != AtomicOrdering::NotAtomic);
3144
3145 writeSyncScope(Context, SSID);
3146 Out << " " << toIRString(ao: SuccessOrdering);
3147 Out << " " << toIRString(ao: FailureOrdering);
3148}
3149
3150void AssemblyWriter::writeParamOperand(const Value *Operand,
3151 AttributeSet Attrs) {
3152 if (!Operand) {
3153 Out << "<null operand!>";
3154 return;
3155 }
3156
3157 // Print the type
3158 TypePrinter.print(Ty: Operand->getType(), OS&: Out);
3159 // Print parameter attributes list
3160 if (Attrs.hasAttributes()) {
3161 Out << ' ';
3162 writeAttributeSet(AttrSet: Attrs);
3163 }
3164 Out << ' ';
3165 // Print the operand
3166 auto WriterCtx = getContext();
3167 writeAsOperandInternal(Out, V: Operand, WriterCtx);
3168}
3169
3170void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
3171 if (!Call->hasOperandBundles())
3172 return;
3173
3174 Out << " [ ";
3175
3176 ListSeparator LS;
3177 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
3178 OperandBundleUse BU = Call->getOperandBundleAt(Index: i);
3179
3180 Out << LS << '"';
3181 printEscapedString(Name: BU.getTagName(), Out);
3182 Out << '"';
3183
3184 Out << '(';
3185
3186 ListSeparator InnerLS;
3187 auto WriterCtx = getContext();
3188 for (const auto &Input : BU.Inputs) {
3189 Out << InnerLS;
3190 if (Input == nullptr)
3191 Out << "<null operand bundle!>";
3192 else
3193 writeAsOperandInternal(Out, V: Input, WriterCtx, /*PrintType=*/true);
3194 }
3195
3196 Out << ')';
3197 }
3198
3199 Out << " ]";
3200}
3201
3202void AssemblyWriter::printModule(const Module *M) {
3203 Machine.initializeIfNeeded();
3204
3205 if (ShouldPreserveUseListOrder)
3206 UseListOrders = predictUseListOrder(M);
3207
3208 if (!M->getModuleIdentifier().empty() &&
3209 // Don't print the ID if it will start a new line (which would
3210 // require a comment char before it).
3211 M->getModuleIdentifier().find(c: '\n') == std::string::npos)
3212 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
3213
3214 if (!M->getSourceFileName().empty()) {
3215 Out << "source_filename = \"";
3216 printEscapedString(Name: M->getSourceFileName(), Out);
3217 Out << "\"\n";
3218 }
3219
3220 const std::string &DL = M->getDataLayoutStr();
3221 if (!DL.empty())
3222 Out << "target datalayout = \"" << DL << "\"\n";
3223 if (!M->getTargetTriple().empty())
3224 Out << "target triple = \"" << M->getTargetTriple().str() << "\"\n";
3225
3226 if (M->hasModuleInlineAsm()) {
3227 Out << '\n';
3228
3229 for (const Module::GlobalAsmFragment &Frag : M->getModuleInlineAsm()) {
3230 Out << "module asm";
3231 SmallVector<std::pair<StringRef, StringRef>> Props =
3232 Frag.Props.getAsStrings();
3233 if (!Props.empty()) {
3234 ListSeparator LS;
3235 Out << "(";
3236 for (auto [Key, Value] : Props) {
3237 Out << LS;
3238 Out << Key << ": \"";
3239 printEscapedString(Name: Value, Out);
3240 Out << "\"";
3241 }
3242 Out << ")";
3243 }
3244 Out << "\n";
3245 // Split the string into lines, to make it easier to read the .ll file.
3246 StringRef Asm = Frag.Asm;
3247 do {
3248 StringRef Front;
3249 std::tie(args&: Front, args&: Asm) = Asm.split(Separator: '\n');
3250
3251 // We found a newline, print the portion of the asm string from the
3252 // last newline up to this newline.
3253 Out << " \"";
3254 printEscapedString(Name: Front, Out);
3255 Out << "\"\n";
3256 } while (!Asm.empty());
3257 }
3258 }
3259
3260 printTypeIdentities();
3261
3262 {
3263 // Output each used comdat at its first global object.
3264 SmallPtrSet<const Comdat *, 8> PrintedComdats;
3265 for (const GlobalObject &GO : M->global_objects()) {
3266 const Comdat *C = GO.getComdat();
3267 if (!C || !PrintedComdats.insert(Ptr: C).second)
3268 continue;
3269 Out << '\n';
3270 printComdat(C);
3271 }
3272 }
3273
3274 // Output all globals.
3275 if (!M->global_empty()) Out << '\n';
3276 for (const GlobalVariable &GV : M->globals()) {
3277 printGlobal(GV: &GV); Out << '\n';
3278 }
3279
3280 // Output all aliases.
3281 if (!M->alias_empty()) Out << "\n";
3282 for (const GlobalAlias &GA : M->aliases())
3283 printAlias(GA: &GA);
3284
3285 // Output all ifuncs.
3286 if (!M->ifunc_empty()) Out << "\n";
3287 for (const GlobalIFunc &GI : M->ifuncs())
3288 printIFunc(GI: &GI);
3289
3290 // Output all of the functions.
3291 for (const Function &F : *M) {
3292 Out << '\n';
3293 printFunction(F: &F);
3294 }
3295
3296 // Output global use-lists.
3297 printUseLists(F: nullptr);
3298
3299 // Output all attribute groups.
3300 if (!Machine.as_empty()) {
3301 Out << '\n';
3302 writeAllAttributeGroups();
3303 }
3304
3305 // Output named metadata.
3306 if (!M->named_metadata_empty()) Out << '\n';
3307
3308 for (const NamedMDNode &Node : M->named_metadata())
3309 printNamedMDNode(NMD: &Node);
3310
3311 // Output metadata.
3312 if (!Machine.mdn_empty()) {
3313 Out << '\n';
3314 writeAllMDNodes();
3315 }
3316}
3317
3318void AssemblyWriter::printModuleSummaryIndex() {
3319 assert(TheIndex);
3320 int NumSlots = Machine.initializeIndexIfNeeded();
3321
3322 Out << "\n";
3323
3324 // Print module path entries. To print in order, add paths to a vector
3325 // indexed by module slot.
3326 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
3327 std::string RegularLTOModuleName =
3328 ModuleSummaryIndex::getRegularLTOModuleName();
3329 moduleVec.resize(new_size: TheIndex->modulePaths().size());
3330 for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
3331 moduleVec[Machine.getModulePathSlot(Path: ModPath)] = std::make_pair(
3332 // An empty module path is a special entry for a regular LTO module
3333 // created during the thin link.
3334 x: ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), y: ModHash);
3335
3336 unsigned i = 0;
3337 for (auto &ModPair : moduleVec) {
3338 Out << "^" << i++ << " = module: (";
3339 Out << "path: \"";
3340 printEscapedString(Name: ModPair.first, Out);
3341 Out << "\", hash: (";
3342 ListSeparator FS;
3343 for (auto Hash : ModPair.second)
3344 Out << FS << Hash;
3345 Out << "))\n";
3346 }
3347
3348 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
3349 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
3350 // Sort by GUID for deterministic output matching slot assignment order.
3351 auto SortedGVS = TheIndex->sortedGlobalValueSummariesRange();
3352
3353 for (const auto &GlobalList : SortedGVS) {
3354 auto GUID = GlobalList.first;
3355 for (auto &Summary : GlobalList.second.getSummaryList())
3356 SummaryToGUIDMap[Summary.get()] = GUID;
3357 }
3358
3359 // Print the global value summary entries.
3360 for (const auto &GlobalList : SortedGVS) {
3361 auto GUID = GlobalList.first;
3362 auto VI = TheIndex->getValueInfo(R: GlobalList);
3363 printSummaryInfo(Slot: Machine.getGUIDSlot(GUID), VI);
3364 }
3365
3366 // Print the TypeIdMap entries.
3367 for (const auto &TID : TheIndex->typeIds()) {
3368 Out << "^" << Machine.getTypeIdSlot(Id: TID.second.first)
3369 << " = typeid: (name: \"" << TID.second.first << "\"";
3370 printTypeIdSummary(TIS: TID.second.second);
3371 Out << ") ; guid = " << TID.first << "\n";
3372 }
3373
3374 // Print the TypeIdCompatibleVtableMap entries.
3375 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
3376 auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: TId.first);
3377 Out << "^" << Machine.getTypeIdCompatibleVtableSlot(Id: TId.first)
3378 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
3379 printTypeIdCompatibleVtableSummary(TI: TId.second);
3380 Out << ") ; guid = " << GUID << "\n";
3381 }
3382
3383 // Don't emit flags when it's not really needed (value is zero by default).
3384 if (TheIndex->getFlags()) {
3385 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
3386 ++NumSlots;
3387 }
3388
3389 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
3390 << "\n";
3391}
3392
3393static const char *
3394getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
3395 switch (K) {
3396 case WholeProgramDevirtResolution::Indir:
3397 return "indir";
3398 case WholeProgramDevirtResolution::SingleImpl:
3399 return "singleImpl";
3400 case WholeProgramDevirtResolution::BranchFunnel:
3401 return "branchFunnel";
3402 }
3403 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
3404}
3405
3406static const char *getWholeProgDevirtResByArgKindName(
3407 WholeProgramDevirtResolution::ByArg::Kind K) {
3408 switch (K) {
3409 case WholeProgramDevirtResolution::ByArg::Indir:
3410 return "indir";
3411 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
3412 return "uniformRetVal";
3413 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
3414 return "uniqueRetVal";
3415 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
3416 return "virtualConstProp";
3417 }
3418 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
3419}
3420
3421static const char *getTTResKindName(TypeTestResolution::Kind K) {
3422 switch (K) {
3423 case TypeTestResolution::Unknown:
3424 return "unknown";
3425 case TypeTestResolution::Unsat:
3426 return "unsat";
3427 case TypeTestResolution::ByteArray:
3428 return "byteArray";
3429 case TypeTestResolution::Inline:
3430 return "inline";
3431 case TypeTestResolution::Single:
3432 return "single";
3433 case TypeTestResolution::AllOnes:
3434 return "allOnes";
3435 }
3436 llvm_unreachable("invalid TypeTestResolution kind");
3437}
3438
3439void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
3440 Out << "typeTestRes: (kind: " << getTTResKindName(K: TTRes.TheKind)
3441 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
3442
3443 // The following fields are only used if the target does not support the use
3444 // of absolute symbols to store constants. Print only if non-zero.
3445 if (TTRes.AlignLog2)
3446 Out << ", alignLog2: " << TTRes.AlignLog2;
3447 if (TTRes.SizeM1)
3448 Out << ", sizeM1: " << TTRes.SizeM1;
3449 if (TTRes.BitMask)
3450 // BitMask is uint8_t which causes it to print the corresponding char.
3451 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
3452 if (TTRes.InlineBits)
3453 Out << ", inlineBits: " << TTRes.InlineBits;
3454
3455 Out << ")";
3456}
3457
3458void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3459 Out << ", summary: (";
3460 printTypeTestResolution(TTRes: TIS.TTRes);
3461 if (!TIS.WPDRes.empty()) {
3462 Out << ", wpdResolutions: (";
3463 ListSeparator FS;
3464 for (auto &WPDRes : TIS.WPDRes) {
3465 Out << FS;
3466 Out << "(offset: " << WPDRes.first << ", ";
3467 printWPDRes(WPDRes: WPDRes.second);
3468 Out << ")";
3469 }
3470 Out << ")";
3471 }
3472 Out << ")";
3473}
3474
3475void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3476 const TypeIdCompatibleVtableInfo &TI) {
3477 Out << ", summary: (";
3478 ListSeparator FS;
3479 for (auto &P : TI) {
3480 Out << FS;
3481 Out << "(offset: " << P.AddressPointOffset << ", ";
3482 Out << "^" << Machine.getGUIDSlot(GUID: P.VTableVI.getGUID());
3483 Out << ")";
3484 }
3485 Out << ")";
3486}
3487
3488void AssemblyWriter::printArgs(ArrayRef<uint64_t> Args) {
3489 Out << "args: (" << llvm::interleaved(R: Args) << ')';
3490}
3491
3492void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3493 Out << "wpdRes: (kind: ";
3494 Out << getWholeProgDevirtResKindName(K: WPDRes.TheKind);
3495
3496 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3497 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3498
3499 if (!WPDRes.ResByArg.empty()) {
3500 Out << ", resByArg: (";
3501 ListSeparator FS;
3502 for (auto &ResByArg : WPDRes.ResByArg) {
3503 Out << FS;
3504 printArgs(Args: ResByArg.first);
3505 Out << ", byArg: (kind: ";
3506 Out << getWholeProgDevirtResByArgKindName(K: ResByArg.second.TheKind);
3507 if (ResByArg.second.TheKind ==
3508 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3509 ResByArg.second.TheKind ==
3510 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3511 Out << ", info: " << ResByArg.second.Info;
3512
3513 // The following fields are only used if the target does not support the
3514 // use of absolute symbols to store constants. Print only if non-zero.
3515 if (ResByArg.second.Byte || ResByArg.second.Bit)
3516 Out << ", byte: " << ResByArg.second.Byte
3517 << ", bit: " << ResByArg.second.Bit;
3518
3519 Out << ")";
3520 }
3521 Out << ")";
3522 }
3523 Out << ")";
3524}
3525
3526static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
3527 switch (SK) {
3528 case GlobalValueSummary::AliasKind:
3529 return "alias";
3530 case GlobalValueSummary::FunctionKind:
3531 return "function";
3532 case GlobalValueSummary::GlobalVarKind:
3533 return "variable";
3534 }
3535 llvm_unreachable("invalid summary kind");
3536}
3537
3538void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3539 Out << ", aliasee: ";
3540 // The indexes emitted for distributed backends may not include the
3541 // aliasee summary (only if it is being imported directly). Handle
3542 // that case by just emitting "null" as the aliasee.
3543 if (AS->hasAliasee())
3544 Out << "^" << Machine.getGUIDSlot(GUID: SummaryToGUIDMap[&AS->getAliasee()]);
3545 else
3546 Out << "null";
3547}
3548
3549void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3550 auto VTableFuncs = GS->vTableFuncs();
3551 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3552 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3553 << "constant: " << GS->VarFlags.Constant;
3554 if (!VTableFuncs.empty())
3555 Out << ", "
3556 << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3557 Out << ")";
3558
3559 if (!VTableFuncs.empty()) {
3560 Out << ", vTableFuncs: (";
3561 ListSeparator FS;
3562 for (auto &P : VTableFuncs) {
3563 Out << FS;
3564 Out << "(virtFunc: ^" << Machine.getGUIDSlot(GUID: P.FuncVI.getGUID())
3565 << ", offset: " << P.VTableOffset;
3566 Out << ")";
3567 }
3568 Out << ")";
3569 }
3570}
3571
3572static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
3573 switch (LT) {
3574 case GlobalValue::ExternalLinkage:
3575 return "external";
3576 case GlobalValue::PrivateLinkage:
3577 return "private";
3578 case GlobalValue::InternalLinkage:
3579 return "internal";
3580 case GlobalValue::LinkOnceAnyLinkage:
3581 return "linkonce";
3582 case GlobalValue::LinkOnceODRLinkage:
3583 return "linkonce_odr";
3584 case GlobalValue::WeakAnyLinkage:
3585 return "weak";
3586 case GlobalValue::WeakODRLinkage:
3587 return "weak_odr";
3588 case GlobalValue::CommonLinkage:
3589 return "common";
3590 case GlobalValue::AppendingLinkage:
3591 return "appending";
3592 case GlobalValue::ExternalWeakLinkage:
3593 return "extern_weak";
3594 case GlobalValue::AvailableExternallyLinkage:
3595 return "available_externally";
3596 }
3597 llvm_unreachable("invalid linkage");
3598}
3599
3600// When printing the linkage types in IR where the ExternalLinkage is
3601// not printed, and other linkage types are expected to be printed with
3602// a space after the name.
3603static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
3604 if (LT == GlobalValue::ExternalLinkage)
3605 return "";
3606 return getLinkageName(LT) + " ";
3607}
3608
3609static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
3610 switch (Vis) {
3611 case GlobalValue::DefaultVisibility:
3612 return "default";
3613 case GlobalValue::HiddenVisibility:
3614 return "hidden";
3615 case GlobalValue::ProtectedVisibility:
3616 return "protected";
3617 }
3618 llvm_unreachable("invalid visibility");
3619}
3620
3621static const char *getImportTypeName(GlobalValueSummary::ImportKind IK) {
3622 switch (IK) {
3623 case GlobalValueSummary::Definition:
3624 return "definition";
3625 case GlobalValueSummary::Declaration:
3626 return "declaration";
3627 }
3628 llvm_unreachable("invalid import kind");
3629}
3630
3631void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3632 Out << ", insts: " << FS->instCount();
3633 if (FS->fflags().anyFlagSet())
3634 Out << ", " << FS->fflags();
3635
3636 if (!FS->calls().empty()) {
3637 Out << ", calls: (";
3638 ListSeparator IFS;
3639 for (auto &Call : FS->calls()) {
3640 Out << IFS;
3641 Out << "(callee: ^" << Machine.getGUIDSlot(GUID: Call.first.getGUID());
3642 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3643 Out << ", hotness: " << getHotnessName(HT: Call.second.getHotness());
3644 // Follow the convention of emitting flags as a boolean value, but only
3645 // emit if true to avoid unnecessary verbosity and test churn.
3646 if (Call.second.HasTailCall)
3647 Out << ", tail: 1";
3648 Out << ")";
3649 }
3650 Out << ")";
3651 }
3652
3653 if (const auto *TIdInfo = FS->getTypeIdInfo())
3654 printTypeIdInfo(TIDInfo: *TIdInfo);
3655
3656 // The AllocationType identifiers capture the profiled context behavior
3657 // reaching a specific static allocation site (possibly cloned).
3658 auto AllocTypeName = [](uint8_t Type) -> const char * {
3659 switch (Type) {
3660 case (uint8_t)AllocationType::None:
3661 return "none";
3662 case (uint8_t)AllocationType::NotCold:
3663 return "notcold";
3664 case (uint8_t)AllocationType::Cold:
3665 return "cold";
3666 case (uint8_t)AllocationType::Hot:
3667 return "hot";
3668 }
3669 llvm_unreachable("Unexpected alloc type");
3670 };
3671
3672 if (!FS->allocs().empty()) {
3673 Out << ", allocs: (";
3674 ListSeparator AFS;
3675 for (auto &AI : FS->allocs()) {
3676 Out << AFS;
3677 Out << "(versions: (";
3678 ListSeparator VFS;
3679 for (auto V : AI.Versions) {
3680 Out << VFS;
3681 Out << AllocTypeName(V);
3682 }
3683 Out << "), memProf: (";
3684 ListSeparator MIBFS;
3685 for (auto &MIB : AI.MIBs) {
3686 Out << MIBFS;
3687 Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3688 Out << ", stackIds: (";
3689 ListSeparator SIDFS;
3690 for (auto Id : MIB.StackIdIndices) {
3691 Out << SIDFS;
3692 Out << TheIndex->getStackIdAtIndex(Index: Id);
3693 }
3694 Out << "))";
3695 }
3696 Out << "))";
3697 }
3698 Out << ")";
3699 }
3700
3701 if (!FS->callsites().empty()) {
3702 Out << ", callsites: (";
3703 ListSeparator SNFS;
3704 for (auto &CI : FS->callsites()) {
3705 Out << SNFS;
3706 if (CI.Callee)
3707 Out << "(callee: ^" << Machine.getGUIDSlot(GUID: CI.Callee.getGUID());
3708 else
3709 Out << "(callee: null";
3710 Out << ", clones: (";
3711 ListSeparator VFS;
3712 for (auto V : CI.Clones) {
3713 Out << VFS;
3714 Out << V;
3715 }
3716 Out << "), stackIds: (";
3717 ListSeparator SIDFS;
3718 for (auto Id : CI.StackIdIndices) {
3719 Out << SIDFS;
3720 Out << TheIndex->getStackIdAtIndex(Index: Id);
3721 }
3722 Out << "))";
3723 }
3724 Out << ")";
3725 }
3726
3727 auto PrintRange = [&](const ConstantRange &Range) {
3728 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3729 };
3730
3731 if (!FS->paramAccesses().empty()) {
3732 Out << ", params: (";
3733 ListSeparator IFS;
3734 for (auto &PS : FS->paramAccesses()) {
3735 Out << IFS;
3736 Out << "(param: " << PS.ParamNo;
3737 Out << ", offset: ";
3738 PrintRange(PS.Use);
3739 if (!PS.Calls.empty()) {
3740 Out << ", calls: (";
3741 ListSeparator IFS;
3742 for (auto &Call : PS.Calls) {
3743 Out << IFS;
3744 Out << "(callee: ^" << Machine.getGUIDSlot(GUID: Call.Callee.getGUID());
3745 Out << ", param: " << Call.ParamNo;
3746 Out << ", offset: ";
3747 PrintRange(Call.Offsets);
3748 Out << ")";
3749 }
3750 Out << ")";
3751 }
3752 Out << ")";
3753 }
3754 Out << ")";
3755 }
3756}
3757
3758void AssemblyWriter::printTypeIdInfo(
3759 const FunctionSummary::TypeIdInfo &TIDInfo) {
3760 Out << ", typeIdInfo: (";
3761 ListSeparator TIDFS;
3762 if (!TIDInfo.TypeTests.empty()) {
3763 Out << TIDFS;
3764 Out << "typeTests: (";
3765 ListSeparator FS;
3766 for (auto &GUID : TIDInfo.TypeTests) {
3767 auto TidIter = TheIndex->typeIds().equal_range(x: GUID);
3768 if (TidIter.first == TidIter.second) {
3769 Out << FS;
3770 Out << GUID;
3771 continue;
3772 }
3773 // Print all type id that correspond to this GUID.
3774 for (const auto &[GUID, TypeIdPair] : make_range(p: TidIter)) {
3775 Out << FS;
3776 auto Slot = Machine.getTypeIdSlot(Id: TypeIdPair.first);
3777 assert(Slot != -1);
3778 Out << "^" << Slot;
3779 }
3780 }
3781 Out << ")";
3782 }
3783 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3784 Out << TIDFS;
3785 printNonConstVCalls(VCallList: TIDInfo.TypeTestAssumeVCalls, Tag: "typeTestAssumeVCalls");
3786 }
3787 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3788 Out << TIDFS;
3789 printNonConstVCalls(VCallList: TIDInfo.TypeCheckedLoadVCalls, Tag: "typeCheckedLoadVCalls");
3790 }
3791 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3792 Out << TIDFS;
3793 printConstVCalls(VCallList: TIDInfo.TypeTestAssumeConstVCalls,
3794 Tag: "typeTestAssumeConstVCalls");
3795 }
3796 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3797 Out << TIDFS;
3798 printConstVCalls(VCallList: TIDInfo.TypeCheckedLoadConstVCalls,
3799 Tag: "typeCheckedLoadConstVCalls");
3800 }
3801 Out << ")";
3802}
3803
3804void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3805 auto TidIter = TheIndex->typeIds().equal_range(x: VFId.GUID);
3806 if (TidIter.first == TidIter.second) {
3807 Out << "vFuncId: (";
3808 Out << "guid: " << VFId.GUID;
3809 Out << ", offset: " << VFId.Offset;
3810 Out << ")";
3811 return;
3812 }
3813 // Print all type id that correspond to this GUID.
3814 ListSeparator FS;
3815 for (const auto &[GUID, TypeIdPair] : make_range(p: TidIter)) {
3816 Out << FS;
3817 Out << "vFuncId: (";
3818 auto Slot = Machine.getTypeIdSlot(Id: TypeIdPair.first);
3819 assert(Slot != -1);
3820 Out << "^" << Slot;
3821 Out << ", offset: " << VFId.Offset;
3822 Out << ")";
3823 }
3824}
3825
3826void AssemblyWriter::printNonConstVCalls(
3827 ArrayRef<FunctionSummary::VFuncId> VCallList, const char *Tag) {
3828 Out << Tag << ": (";
3829 ListSeparator FS;
3830 for (auto &VFuncId : VCallList) {
3831 Out << FS;
3832 printVFuncId(VFId: VFuncId);
3833 }
3834 Out << ")";
3835}
3836
3837void AssemblyWriter::printConstVCalls(
3838 ArrayRef<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3839 Out << Tag << ": (";
3840 ListSeparator FS;
3841 for (auto &ConstVCall : VCallList) {
3842 Out << FS;
3843 Out << "(";
3844 printVFuncId(VFId: ConstVCall.VFunc);
3845 if (!ConstVCall.Args.empty()) {
3846 Out << ", ";
3847 printArgs(Args: ConstVCall.Args);
3848 }
3849 Out << ")";
3850 }
3851 Out << ")";
3852}
3853
3854void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3855 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3856 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3857 Out << getSummaryKindName(SK: Summary.getSummaryKind()) << ": ";
3858 Out << "(module: ^" << Machine.getModulePathSlot(Path: Summary.modulePath())
3859 << ", flags: (";
3860 Out << "linkage: " << getLinkageName(LT);
3861 Out << ", visibility: "
3862 << getVisibilityName(Vis: (GlobalValue::VisibilityTypes)GVFlags.Visibility);
3863 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3864 Out << ", live: " << GVFlags.Live;
3865 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3866 Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3867 Out << ", importType: "
3868 << getImportTypeName(IK: GlobalValueSummary::ImportKind(GVFlags.ImportType));
3869 Out << ", noRenameOnPromotion: " << GVFlags.NoRenameOnPromotion;
3870 Out << ")";
3871
3872 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3873 printAliasSummary(AS: cast<AliasSummary>(Val: &Summary));
3874 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3875 printFunctionSummary(FS: cast<FunctionSummary>(Val: &Summary));
3876 else
3877 printGlobalVarSummary(GS: cast<GlobalVarSummary>(Val: &Summary));
3878
3879 auto RefList = Summary.refs();
3880 if (!RefList.empty()) {
3881 Out << ", refs: (";
3882 ListSeparator FS;
3883 for (auto &Ref : RefList) {
3884 Out << FS;
3885 if (Ref.isReadOnly())
3886 Out << "readonly ";
3887 else if (Ref.isWriteOnly())
3888 Out << "writeonly ";
3889 Out << "^" << Machine.getGUIDSlot(GUID: Ref.getGUID());
3890 }
3891 Out << ")";
3892 }
3893
3894 Out << ")";
3895}
3896
3897void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3898 Out << "^" << Slot << " = gv: (";
3899 if (VI.hasName() && !VI.name().empty())
3900 Out << "name: \"" << VI.name() << "\"";
3901 else
3902 Out << "guid: " << VI.getGUID();
3903 if (!VI.getSummaryList().empty()) {
3904 Out << ", summaries: (";
3905 ListSeparator FS;
3906 for (auto &Summary : VI.getSummaryList()) {
3907 Out << FS;
3908 printSummary(Summary: *Summary);
3909 }
3910 Out << ")";
3911 }
3912 Out << ")";
3913 if (VI.hasName() && !VI.name().empty())
3914 Out << " ; guid = " << VI.getGUID();
3915 Out << "\n";
3916}
3917
3918static void printMetadataIdentifier(StringRef Name,
3919 formatted_raw_ostream &Out) {
3920 if (Name.empty()) {
3921 Out << "<empty name> ";
3922 } else {
3923 unsigned char FirstC = static_cast<unsigned char>(Name[0]);
3924 if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||
3925 FirstC == '_')
3926 Out << FirstC;
3927 else
3928 Out << '\\' << hexdigit(X: FirstC >> 4) << hexdigit(X: FirstC & 0x0F);
3929 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3930 unsigned char C = Name[i];
3931 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
3932 Out << C;
3933 else
3934 Out << '\\' << hexdigit(X: C >> 4) << hexdigit(X: C & 0x0F);
3935 }
3936 }
3937}
3938
3939void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3940 Out << '!';
3941 printMetadataIdentifier(Name: NMD->getName(), Out);
3942 Out << " = !{";
3943 ListSeparator LS;
3944 for (const MDNode *Op : NMD->operands()) {
3945 Out << LS;
3946 // Write DIExpressions inline.
3947 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3948 if (auto *Expr = dyn_cast<DIExpression>(Val: Op)) {
3949 writeDIExpression(Out, N: Expr, WriterCtx&: AsmWriterContext::getEmpty());
3950 continue;
3951 }
3952
3953 int Slot = Machine.getMetadataSlot(N: Op);
3954 if (Slot == -1)
3955 Out << "<badref>";
3956 else
3957 Out << '!' << Slot;
3958 }
3959 Out << "}\n";
3960}
3961
3962static void printVisibility(GlobalValue::VisibilityTypes Vis,
3963 formatted_raw_ostream &Out) {
3964 switch (Vis) {
3965 case GlobalValue::DefaultVisibility: break;
3966 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3967 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3968 }
3969}
3970
3971static void printDSOLocation(const GlobalValue &GV,
3972 formatted_raw_ostream &Out) {
3973 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3974 Out << "dso_local ";
3975}
3976
3977static void printDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3978 formatted_raw_ostream &Out) {
3979 switch (SCT) {
3980 case GlobalValue::DefaultStorageClass: break;
3981 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3982 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3983 }
3984}
3985
3986static void printThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3987 formatted_raw_ostream &Out) {
3988 switch (TLM) {
3989 case GlobalVariable::NotThreadLocal:
3990 break;
3991 case GlobalVariable::GeneralDynamicTLSModel:
3992 Out << "thread_local ";
3993 break;
3994 case GlobalVariable::LocalDynamicTLSModel:
3995 Out << "thread_local(localdynamic) ";
3996 break;
3997 case GlobalVariable::InitialExecTLSModel:
3998 Out << "thread_local(initialexec) ";
3999 break;
4000 case GlobalVariable::LocalExecTLSModel:
4001 Out << "thread_local(localexec) ";
4002 break;
4003 }
4004}
4005
4006static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
4007 switch (UA) {
4008 case GlobalVariable::UnnamedAddr::None:
4009 return "";
4010 case GlobalVariable::UnnamedAddr::Local:
4011 return "local_unnamed_addr";
4012 case GlobalVariable::UnnamedAddr::Global:
4013 return "unnamed_addr";
4014 }
4015 llvm_unreachable("Unknown UnnamedAddr");
4016}
4017
4018static void maybePrintComdat(formatted_raw_ostream &Out,
4019 const GlobalObject &GO) {
4020 const Comdat *C = GO.getComdat();
4021 if (!C)
4022 return;
4023
4024 if (isa<GlobalVariable>(Val: GO))
4025 Out << ',';
4026 Out << " comdat";
4027
4028 if (GO.getName() == C->getName())
4029 return;
4030
4031 Out << '(';
4032 printLLVMName(OS&: Out, Name: C->getName(), Prefix: ComdatPrefix);
4033 Out << ')';
4034}
4035
4036void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
4037 if (GV->isMaterializable())
4038 Out << "; Materializable\n";
4039
4040 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
4041 writeAsOperandInternal(Out, V: GV, WriterCtx);
4042 Out << " = ";
4043
4044 if (!GV->hasInitializer() && GV->hasExternalLinkage())
4045 Out << "external ";
4046
4047 Out << getLinkageNameWithSpace(LT: GV->getLinkage());
4048 printDSOLocation(GV: *GV, Out);
4049 printVisibility(Vis: GV->getVisibility(), Out);
4050 printDLLStorageClass(SCT: GV->getDLLStorageClass(), Out);
4051 printThreadLocalModel(TLM: GV->getThreadLocalMode(), Out);
4052 StringRef UA = getUnnamedAddrEncoding(UA: GV->getUnnamedAddr());
4053 if (!UA.empty())
4054 Out << UA << ' ';
4055
4056 printAddressSpace(M: GV->getParent(), AS: GV->getType()->getAddressSpace(), OS&: Out,
4057 /*Prefix=*/"", /*Suffix=*/" ");
4058 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
4059 Out << (GV->isConstant() ? "constant " : "global ");
4060 TypePrinter.print(Ty: GV->getValueType(), OS&: Out);
4061
4062 if (GV->hasInitializer()) {
4063 Out << ' ';
4064 writeOperand(Operand: GV->getInitializer(), PrintType: false);
4065 }
4066
4067 if (GV->hasSection()) {
4068 Out << ", section \"";
4069 printEscapedString(Name: GV->getSection(), Out);
4070 Out << '"';
4071 }
4072 if (GV->hasPartition()) {
4073 Out << ", partition \"";
4074 printEscapedString(Name: GV->getPartition(), Out);
4075 Out << '"';
4076 }
4077 if (auto CM = GV->getCodeModel()) {
4078 Out << ", code_model \"";
4079 switch (*CM) {
4080 case CodeModel::Tiny:
4081 Out << "tiny";
4082 break;
4083 case CodeModel::Small:
4084 Out << "small";
4085 break;
4086 case CodeModel::Kernel:
4087 Out << "kernel";
4088 break;
4089 case CodeModel::Medium:
4090 Out << "medium";
4091 break;
4092 case CodeModel::Large:
4093 Out << "large";
4094 break;
4095 }
4096 Out << '"';
4097 }
4098
4099 using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
4100 if (GV->hasSanitizerMetadata()) {
4101 SanitizerMetadata MD = GV->getSanitizerMetadata();
4102 if (MD.NoAddress)
4103 Out << ", no_sanitize_address";
4104 if (MD.NoHWAddress)
4105 Out << ", no_sanitize_hwaddress";
4106 if (MD.Memtag)
4107 Out << ", sanitize_memtag";
4108 if (MD.IsDynInit)
4109 Out << ", sanitize_address_dyninit";
4110 }
4111
4112 maybePrintComdat(Out, GO: *GV);
4113 if (MaybeAlign A = GV->getAlign())
4114 Out << ", align " << A->value();
4115
4116 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4117 GV->getAllMetadata(MDs);
4118 printMetadataAttachments(MDs, Separator: ", ");
4119
4120 auto Attrs = GV->getAttributes();
4121 if (Attrs.hasAttributes())
4122 Out << " #" << Machine.getAttributeGroupSlot(AS: Attrs);
4123
4124 printInfoComment(V: *GV, isMaterializable: GV->isMaterializable());
4125}
4126
4127void AssemblyWriter::printAlias(const GlobalAlias *GA) {
4128 if (GA->isMaterializable())
4129 Out << "; Materializable\n";
4130
4131 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
4132 writeAsOperandInternal(Out, V: GA, WriterCtx);
4133 Out << " = ";
4134
4135 Out << getLinkageNameWithSpace(LT: GA->getLinkage());
4136 printDSOLocation(GV: *GA, Out);
4137 printVisibility(Vis: GA->getVisibility(), Out);
4138 printDLLStorageClass(SCT: GA->getDLLStorageClass(), Out);
4139 printThreadLocalModel(TLM: GA->getThreadLocalMode(), Out);
4140 StringRef UA = getUnnamedAddrEncoding(UA: GA->getUnnamedAddr());
4141 if (!UA.empty())
4142 Out << UA << ' ';
4143
4144 Out << "alias ";
4145
4146 TypePrinter.print(Ty: GA->getValueType(), OS&: Out);
4147 Out << ", ";
4148
4149 if (const Constant *Aliasee = GA->getAliasee()) {
4150 writeOperand(Operand: Aliasee, PrintType: !isa<ConstantExpr>(Val: Aliasee));
4151 } else {
4152 TypePrinter.print(Ty: GA->getType(), OS&: Out);
4153 Out << " <<NULL ALIASEE>>";
4154 }
4155
4156 if (GA->hasPartition()) {
4157 Out << ", partition \"";
4158 printEscapedString(Name: GA->getPartition(), Out);
4159 Out << '"';
4160 }
4161
4162 printInfoComment(V: *GA, isMaterializable: GA->isMaterializable());
4163 Out << '\n';
4164}
4165
4166void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
4167 if (GI->isMaterializable())
4168 Out << "; Materializable\n";
4169
4170 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
4171 writeAsOperandInternal(Out, V: GI, WriterCtx);
4172 Out << " = ";
4173
4174 Out << getLinkageNameWithSpace(LT: GI->getLinkage());
4175 printDSOLocation(GV: *GI, Out);
4176 printVisibility(Vis: GI->getVisibility(), Out);
4177
4178 Out << "ifunc ";
4179
4180 TypePrinter.print(Ty: GI->getValueType(), OS&: Out);
4181 Out << ", ";
4182
4183 if (const Constant *Resolver = GI->getResolver()) {
4184 writeOperand(Operand: Resolver, PrintType: !isa<ConstantExpr>(Val: Resolver));
4185 } else {
4186 TypePrinter.print(Ty: GI->getType(), OS&: Out);
4187 Out << " <<NULL RESOLVER>>";
4188 }
4189
4190 if (GI->hasPartition()) {
4191 Out << ", partition \"";
4192 printEscapedString(Name: GI->getPartition(), Out);
4193 Out << '"';
4194 }
4195 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4196 GI->getAllMetadata(MDs);
4197 if (!MDs.empty()) {
4198 printMetadataAttachments(MDs, Separator: ", ");
4199 }
4200
4201 printInfoComment(V: *GI, isMaterializable: GI->isMaterializable());
4202 Out << '\n';
4203}
4204
4205void AssemblyWriter::printComdat(const Comdat *C) {
4206 C->print(OS&: Out);
4207}
4208
4209void AssemblyWriter::printTypeIdentities() {
4210 if (TypePrinter.empty())
4211 return;
4212
4213 Out << '\n';
4214
4215 // Emit all numbered types.
4216 auto &NumberedTypes = TypePrinter.getNumberedTypes();
4217 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
4218 Out << '%' << I << " = type ";
4219
4220 // Make sure we print out at least one level of the type structure, so
4221 // that we do not get %2 = type %2
4222 TypePrinter.printStructBody(STy: NumberedTypes[I], OS&: Out);
4223 Out << '\n';
4224 }
4225
4226 auto &NamedTypes = TypePrinter.getNamedTypes();
4227 for (StructType *NamedType : NamedTypes) {
4228 printLLVMName(OS&: Out, Name: NamedType->getName(), Prefix: LocalPrefix);
4229 Out << " = type ";
4230
4231 // Make sure we print out at least one level of the type structure, so
4232 // that we do not get %FILE = type %FILE
4233 TypePrinter.printStructBody(STy: NamedType, OS&: Out);
4234 Out << '\n';
4235 }
4236}
4237
4238/// printFunction - Print all aspects of a function.
4239void AssemblyWriter::printFunction(const Function *F) {
4240 if (F->isMaterializable())
4241 Out << "; Materializable\n";
4242 else if (AnnotationWriter)
4243 AnnotationWriter->emitFunctionAnnot(F, Out);
4244
4245 const AttributeList &Attrs = F->getAttributes();
4246 if (Attrs.hasFnAttrs()) {
4247 AttributeSet AS = Attrs.getFnAttrs();
4248 std::string AttrStr;
4249
4250 for (const Attribute &Attr : AS) {
4251 if (!Attr.isStringAttribute()) {
4252 if (!AttrStr.empty()) AttrStr += ' ';
4253 AttrStr += Attr.getAsString();
4254 }
4255 }
4256
4257 if (!AttrStr.empty())
4258 Out << "; Function Attrs: " << AttrStr << '\n';
4259 }
4260
4261 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::not_intrinsic)
4262 Out << "; Unknown intrinsic\n";
4263
4264 Machine.incorporateFunction(F);
4265
4266 if (F->isDeclaration()) {
4267 Out << "declare";
4268 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4269 F->getAllMetadata(MDs);
4270 printMetadataAttachments(MDs, Separator: " ");
4271 Out << ' ';
4272 } else
4273 Out << "define ";
4274
4275 Out << getLinkageNameWithSpace(LT: F->getLinkage());
4276 printDSOLocation(GV: *F, Out);
4277 printVisibility(Vis: F->getVisibility(), Out);
4278 printDLLStorageClass(SCT: F->getDLLStorageClass(), Out);
4279
4280 // Print the calling convention.
4281 if (F->getCallingConv() != CallingConv::C) {
4282 printCallingConv(cc: F->getCallingConv(), Out);
4283 Out << " ";
4284 }
4285
4286 FunctionType *FT = F->getFunctionType();
4287 if (Attrs.hasRetAttrs())
4288 Out << Attrs.getAsString(Index: AttributeList::ReturnIndex) << ' ';
4289 TypePrinter.print(Ty: F->getReturnType(), OS&: Out);
4290 AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
4291 Out << ' ';
4292 writeAsOperandInternal(Out, V: F, WriterCtx);
4293 Out << '(';
4294
4295 // Loop over the arguments, printing them...
4296 if (F->isDeclaration() && !IsForDebug) {
4297 // We're only interested in the type here - don't print argument names.
4298 ListSeparator LS;
4299 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
4300 Out << LS;
4301 // Output type.
4302 TypePrinter.print(Ty: FT->getParamType(i: I), OS&: Out);
4303
4304 AttributeSet ArgAttrs = Attrs.getParamAttrs(ArgNo: I);
4305 if (ArgAttrs.hasAttributes()) {
4306 Out << ' ';
4307 writeAttributeSet(AttrSet: ArgAttrs);
4308 }
4309 }
4310 } else {
4311 // The arguments are meaningful here, print them in detail.
4312 ListSeparator LS;
4313 for (const Argument &Arg : F->args()) {
4314 Out << LS;
4315 printArgument(FA: &Arg, Attrs: Attrs.getParamAttrs(ArgNo: Arg.getArgNo()));
4316 }
4317 }
4318
4319 // Finish printing arguments...
4320 if (FT->isVarArg()) {
4321 if (FT->getNumParams()) Out << ", ";
4322 Out << "..."; // Output varargs portion of signature!
4323 }
4324 Out << ')';
4325 StringRef UA = getUnnamedAddrEncoding(UA: F->getUnnamedAddr());
4326 if (!UA.empty())
4327 Out << ' ' << UA;
4328 // We print the function address space if it is non-zero or if we are writing
4329 // a module with a non-zero program address space or if there is no valid
4330 // Module* so that the file can be parsed without the datalayout string.
4331 const Module *Mod = F->getParent();
4332 bool ForcePrintAddressSpace =
4333 !Mod || Mod->getDataLayout().getProgramAddressSpace() != 0;
4334 printAddressSpace(M: Mod, AS: F->getAddressSpace(), OS&: Out, /*Prefix=*/" ",
4335 /*Suffix=*/"", ForcePrint: ForcePrintAddressSpace);
4336 if (Attrs.hasFnAttrs())
4337 Out << " #" << Machine.getAttributeGroupSlot(AS: Attrs.getFnAttrs());
4338 if (F->hasSection()) {
4339 Out << " section \"";
4340 printEscapedString(Name: F->getSection(), Out);
4341 Out << '"';
4342 }
4343 if (F->hasPartition()) {
4344 Out << " partition \"";
4345 printEscapedString(Name: F->getPartition(), Out);
4346 Out << '"';
4347 }
4348 maybePrintComdat(Out, GO: *F);
4349 if (MaybeAlign A = F->getAlign())
4350 Out << " align " << A->value();
4351 if (MaybeAlign A = F->getPreferredAlignment())
4352 Out << " prefalign(" << A->value() << ')';
4353 if (F->hasGC())
4354 Out << " gc \"" << F->getGC() << '"';
4355 if (F->hasPrefixData()) {
4356 Out << " prefix ";
4357 writeOperand(Operand: F->getPrefixData(), PrintType: true);
4358 }
4359 if (F->hasPrologueData()) {
4360 Out << " prologue ";
4361 writeOperand(Operand: F->getPrologueData(), PrintType: true);
4362 }
4363 if (F->hasPersonalityFn()) {
4364 Out << " personality ";
4365 writeOperand(Operand: F->getPersonalityFn(), /*PrintType=*/true);
4366 }
4367
4368 if (PrintProfData) {
4369 if (auto *MDProf = F->getMetadata(KindID: LLVMContext::MD_prof)) {
4370 Out << " ";
4371 MDProf->print(OS&: Out, M: TheModule, /*IsForDebug=*/true);
4372 }
4373 }
4374
4375 if (F->isDeclaration()) {
4376 Out << '\n';
4377 } else {
4378 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4379 F->getAllMetadata(MDs);
4380 printMetadataAttachments(MDs, Separator: " ");
4381
4382 Out << " {";
4383 // Output all of the function's basic blocks.
4384 for (const BasicBlock &BB : *F)
4385 printBasicBlock(BB: &BB);
4386
4387 // Output the function's use-lists.
4388 printUseLists(F);
4389
4390 Out << "}\n";
4391 }
4392
4393 Machine.purgeFunction();
4394}
4395
4396/// printArgument - This member is called for every argument that is passed into
4397/// the function. Simply print it out
4398void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
4399 // Output type...
4400 TypePrinter.print(Ty: Arg->getType(), OS&: Out);
4401
4402 // Output parameter attributes list
4403 if (Attrs.hasAttributes()) {
4404 Out << ' ';
4405 writeAttributeSet(AttrSet: Attrs);
4406 }
4407
4408 // Output name, if available...
4409 if (Arg->hasName()) {
4410 Out << ' ';
4411 printLLVMName(OS&: Out, V: Arg);
4412 } else {
4413 int Slot = Machine.getLocalSlot(V: Arg);
4414 assert(Slot != -1 && "expect argument in function here");
4415 Out << " %" << Slot;
4416 }
4417}
4418
4419/// printBasicBlock - This member is called for each basic block in a method.
4420void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
4421 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
4422 if (BB->hasName()) { // Print out the label if it exists...
4423 Out << "\n";
4424 printLLVMName(OS&: Out, Name: BB->getName(), Prefix: LabelPrefix);
4425 Out << ':';
4426 } else if (!IsEntryBlock) {
4427 Out << "\n";
4428 int Slot = Machine.getLocalSlot(V: BB);
4429 if (Slot != -1)
4430 Out << Slot << ":";
4431 else
4432 Out << "<badref>:";
4433 }
4434
4435 if (!IsEntryBlock) {
4436 // Output predecessors for the block.
4437 Out.PadToColumn(NewCol: 50);
4438 Out << ";";
4439 if (pred_empty(BB)) {
4440 Out << " No predecessors!";
4441 } else {
4442 Out << " preds = ";
4443 ListSeparator LS;
4444 for (const BasicBlock *Pred : predecessors(BB)) {
4445 Out << LS;
4446 writeOperand(Operand: Pred, PrintType: false);
4447 }
4448 }
4449 }
4450
4451 Out << "\n";
4452
4453 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
4454
4455 // Output all of the instructions in the basic block...
4456 for (const Instruction &I : *BB) {
4457 for (const DbgRecord &DR : I.getDbgRecordRange())
4458 printDbgRecordLine(DR);
4459 printInstructionLine(I);
4460 }
4461
4462 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
4463}
4464
4465/// printInstructionLine - Print an instruction and a newline character.
4466void AssemblyWriter::printInstructionLine(const Instruction &I) {
4467 printInstruction(I);
4468 Out << '\n';
4469}
4470
4471/// printGCRelocateComment - print comment after call to the gc.relocate
4472/// intrinsic indicating base and derived pointer names.
4473void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
4474 Out << " ; (";
4475 if (Value *BasePtr = Relocate.getBasePtr())
4476 writeOperand(Operand: BasePtr, PrintType: false);
4477 else
4478 Out << "invalid";
4479 Out << ", ";
4480 if (Value *DerivedPtr = Relocate.getDerivedPtr())
4481 writeOperand(Operand: DerivedPtr, PrintType: false);
4482 else
4483 Out << "invalid";
4484 Out << ")";
4485}
4486
4487/// printInfoComment - Print a little comment after the instruction indicating
4488/// which slot it occupies.
4489void AssemblyWriter::printInfoComment(const Value &V, bool isMaterializable) {
4490 if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val: &V))
4491 printGCRelocateComment(Relocate: *Relocate);
4492
4493 if (AnnotationWriter && !isMaterializable)
4494 AnnotationWriter->printInfoComment(V, Out);
4495
4496 if (PrintInstDebugLocs) {
4497 if (auto *I = dyn_cast<Instruction>(Val: &V)) {
4498 if (I->getDebugLoc()) {
4499 Out << " ; ";
4500 I->getDebugLoc().print(OS&: Out);
4501 }
4502 }
4503 }
4504 if (PrintProfData) {
4505 if (auto *I = dyn_cast<Instruction>(Val: &V)) {
4506 if (auto *MD = I->getMetadata(KindID: LLVMContext::MD_prof)) {
4507 Out << " ; ";
4508 MD->print(OS&: Out, M: TheModule, /*IsForDebug=*/true);
4509 }
4510 }
4511 }
4512
4513 if (PrintInstAddrs)
4514 Out << " ; " << &V;
4515}
4516
4517static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
4518 raw_ostream &Out) {
4519 if (Operand == nullptr) {
4520 Out << " <cannot get addrspace!>";
4521 return;
4522 }
4523
4524 // We print the address space of the call if it is non-zero.
4525 // We also print it if it is zero but not equal to the program address space
4526 // or if we can't find a valid Module* to make it possible to parse
4527 // the resulting file even without a datalayout string.
4528 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
4529 const Module *Mod = getModuleFromVal(V: I);
4530 bool ForcePrintAddrSpace =
4531 !Mod || Mod->getDataLayout().getProgramAddressSpace() != 0;
4532 printAddressSpace(M: Mod, AS: CallAddrSpace, OS&: Out, /*Prefix=*/" ", /*Suffix=*/"",
4533 ForcePrint: ForcePrintAddrSpace);
4534}
4535
4536// This member is called for each Instruction in a function..
4537void AssemblyWriter::printInstruction(const Instruction &I) {
4538 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
4539
4540 // Print out indentation for an instruction.
4541 Out << " ";
4542
4543 // Print out name if it exists...
4544 if (I.hasName()) {
4545 printLLVMName(OS&: Out, V: &I);
4546 Out << " = ";
4547 } else if (!I.getType()->isVoidTy()) {
4548 // Print out the def slot taken.
4549 int SlotNum = Machine.getLocalSlot(V: &I);
4550 if (SlotNum == -1)
4551 Out << "<badref> = ";
4552 else
4553 Out << '%' << SlotNum << " = ";
4554 }
4555
4556 if (const auto *CI = dyn_cast<CallInst>(Val: &I)) {
4557 if (CI->isMustTailCall())
4558 Out << "musttail ";
4559 else if (CI->isTailCall())
4560 Out << "tail ";
4561 else if (CI->isNoTailCall())
4562 Out << "notail ";
4563 }
4564
4565 // Print out the opcode...
4566 Out << I.getOpcodeName();
4567
4568 // If this is an atomic load or store, print out the atomic marker.
4569 if ((isa<LoadInst>(Val: I) && cast<LoadInst>(Val: I).isAtomic()) ||
4570 (isa<StoreInst>(Val: I) && cast<StoreInst>(Val: I).isAtomic()))
4571 Out << " atomic";
4572
4573 if (isa<AtomicCmpXchgInst>(Val: I) && cast<AtomicCmpXchgInst>(Val: I).isWeak())
4574 Out << " weak";
4575
4576 // If this is a volatile operation, print out the volatile marker.
4577 if ((isa<LoadInst>(Val: I) && cast<LoadInst>(Val: I).isVolatile()) ||
4578 (isa<StoreInst>(Val: I) && cast<StoreInst>(Val: I).isVolatile()) ||
4579 (isa<AtomicCmpXchgInst>(Val: I) && cast<AtomicCmpXchgInst>(Val: I).isVolatile()) ||
4580 (isa<AtomicRMWInst>(Val: I) && cast<AtomicRMWInst>(Val: I).isVolatile()))
4581 Out << " volatile";
4582
4583 // Print the elementwise marker for atomic loads and stores.
4584 if ((isa<LoadInst>(Val: I) && cast<LoadInst>(Val: I).isElementwise()) ||
4585 (isa<StoreInst>(Val: I) && cast<StoreInst>(Val: I).isElementwise()))
4586 Out << " elementwise";
4587
4588 // Print out optimization information.
4589 writeOptimizationInfo(Out, U: &I);
4590
4591 // Print out the compare instruction predicates
4592 if (const auto *CI = dyn_cast<CmpInst>(Val: &I))
4593 Out << ' ' << CI->getPredicate();
4594
4595 // Print out the atomicrmw operation
4596 if (const auto *RMWI = dyn_cast<AtomicRMWInst>(Val: &I)) {
4597 if (RMWI->isElementwise())
4598 Out << " elementwise";
4599 Out << ' ' << AtomicRMWInst::getOperationName(Op: RMWI->getOperation());
4600 }
4601
4602 // Print out the type of the operands...
4603 const Value *Operand = I.getNumOperands() ? I.getOperand(i: 0) : nullptr;
4604
4605 // Special case conditional branches to swizzle the condition out to the front
4606 if (const auto *BI = dyn_cast<CondBrInst>(Val: &I)) {
4607 Out << ' ';
4608 writeOperand(Operand: BI->getCondition(), PrintType: true);
4609 Out << ", ";
4610 writeOperand(Operand: BI->getSuccessor(i: 0), PrintType: true);
4611 Out << ", ";
4612 writeOperand(Operand: BI->getSuccessor(i: 1), PrintType: true);
4613 } else if (isa<SwitchInst>(Val: I)) {
4614 const SwitchInst& SI(cast<SwitchInst>(Val: I));
4615 // Special case switch instruction to get formatting nice and correct.
4616 Out << ' ';
4617 writeOperand(Operand: SI.getCondition(), PrintType: true);
4618 Out << ", ";
4619 writeOperand(Operand: SI.getDefaultDest(), PrintType: true);
4620 Out << " [";
4621 for (auto Case : SI.cases()) {
4622 Out << "\n ";
4623 writeOperand(Operand: Case.getCaseValue(), PrintType: true);
4624 Out << ", ";
4625 writeOperand(Operand: Case.getCaseSuccessor(), PrintType: true);
4626 }
4627 Out << "\n ]";
4628 } else if (isa<IndirectBrInst>(Val: I)) {
4629 // Special case indirectbr instruction to get formatting nice and correct.
4630 Out << ' ';
4631 writeOperand(Operand, PrintType: true);
4632 Out << ", [";
4633
4634 ListSeparator LS;
4635 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
4636 Out << LS;
4637 writeOperand(Operand: I.getOperand(i), PrintType: true);
4638 }
4639 Out << ']';
4640 } else if (const auto *PN = dyn_cast<PHINode>(Val: &I)) {
4641 Out << ' ';
4642 TypePrinter.print(Ty: I.getType(), OS&: Out);
4643 Out << ' ';
4644
4645 ListSeparator LS;
4646 for (const auto &[V, Block] :
4647 zip_equal(t: PN->incoming_values(), u: PN->blocks())) {
4648 Out << LS << "[ ";
4649 writeOperand(Operand: V, PrintType: false);
4650 Out << ", ";
4651 writeOperand(Operand: Block, PrintType: false);
4652 Out << " ]";
4653 }
4654 } else if (const auto *EVI = dyn_cast<ExtractValueInst>(Val: &I)) {
4655 Out << ' ';
4656 writeOperand(Operand: I.getOperand(i: 0), PrintType: true);
4657 Out << ", ";
4658 Out << llvm::interleaved(R: EVI->indices());
4659 } else if (const auto *IVI = dyn_cast<InsertValueInst>(Val: &I)) {
4660 Out << ' ';
4661 writeOperand(Operand: I.getOperand(i: 0), PrintType: true); Out << ", ";
4662 writeOperand(Operand: I.getOperand(i: 1), PrintType: true);
4663 Out << ", ";
4664 Out << llvm::interleaved(R: IVI->indices());
4665 } else if (const auto *LPI = dyn_cast<LandingPadInst>(Val: &I)) {
4666 Out << ' ';
4667 TypePrinter.print(Ty: I.getType(), OS&: Out);
4668 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4669 Out << '\n';
4670
4671 if (LPI->isCleanup())
4672 Out << " cleanup";
4673
4674 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4675 if (i != 0 || LPI->isCleanup()) Out << "\n";
4676 if (LPI->isCatch(Idx: i))
4677 Out << " catch ";
4678 else
4679 Out << " filter ";
4680
4681 writeOperand(Operand: LPI->getClause(Idx: i), PrintType: true);
4682 }
4683 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val: &I)) {
4684 Out << " within ";
4685 writeOperand(Operand: CatchSwitch->getParentPad(), /*PrintType=*/false);
4686 Out << " [";
4687 ListSeparator LS;
4688 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4689 Out << LS;
4690 writeOperand(Operand: PadBB, /*PrintType=*/true);
4691 }
4692 Out << "] unwind ";
4693 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4694 writeOperand(Operand: UnwindDest, /*PrintType=*/true);
4695 else
4696 Out << "to caller";
4697 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(Val: &I)) {
4698 Out << " within ";
4699 writeOperand(Operand: FPI->getParentPad(), /*PrintType=*/false);
4700 Out << " [";
4701 ListSeparator LS;
4702 for (const Value *Op : FPI->arg_operands()) {
4703 Out << LS;
4704 writeOperand(Operand: Op, /*PrintType=*/true);
4705 }
4706 Out << ']';
4707 } else if (isa<ReturnInst>(Val: I) && !Operand) {
4708 Out << " void";
4709 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(Val: &I)) {
4710 Out << " from ";
4711 writeOperand(Operand: CRI->getOperand(i_nocapture: 0), /*PrintType=*/false);
4712
4713 Out << " to ";
4714 writeOperand(Operand: CRI->getOperand(i_nocapture: 1), /*PrintType=*/true);
4715 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val: &I)) {
4716 Out << " from ";
4717 writeOperand(Operand: CRI->getOperand(i_nocapture: 0), /*PrintType=*/false);
4718
4719 Out << " unwind ";
4720 if (CRI->hasUnwindDest())
4721 writeOperand(Operand: CRI->getOperand(i_nocapture: 1), /*PrintType=*/true);
4722 else
4723 Out << "to caller";
4724 } else if (const auto *CI = dyn_cast<CallInst>(Val: &I)) {
4725 // Print the calling convention being used.
4726 if (CI->getCallingConv() != CallingConv::C) {
4727 Out << " ";
4728 printCallingConv(cc: CI->getCallingConv(), Out);
4729 }
4730
4731 Operand = CI->getCalledOperand();
4732 FunctionType *FTy = CI->getFunctionType();
4733 Type *RetTy = FTy->getReturnType();
4734 const AttributeList &PAL = CI->getAttributes();
4735
4736 if (PAL.hasRetAttrs())
4737 Out << ' ' << PAL.getAsString(Index: AttributeList::ReturnIndex);
4738
4739 // Only print addrspace(N) if necessary:
4740 maybePrintCallAddrSpace(Operand, I: &I, Out);
4741
4742 // If possible, print out the short form of the call instruction. We can
4743 // only do this if the first argument is a pointer to a nonvararg function,
4744 // and if the return type is not a pointer to a function.
4745 Out << ' ';
4746 TypePrinter.print(Ty: FTy->isVarArg() ? FTy : RetTy, OS&: Out);
4747 Out << ' ';
4748 writeOperand(Operand, PrintType: false);
4749 Out << '(';
4750 bool HasPrettyPrintedArgs =
4751 isa<IntrinsicInst>(Val: CI) &&
4752 Intrinsic::hasPrettyPrintedArgs(id: CI->getIntrinsicID());
4753
4754 ListSeparator LS;
4755 Function *CalledFunc = CI->getCalledFunction();
4756 auto PrintArgComment = [&](unsigned ArgNo) {
4757 const auto *ConstArg = dyn_cast<Constant>(Val: CI->getArgOperand(i: ArgNo));
4758 if (!ConstArg || !CalledFunc)
4759 return;
4760 std::string ArgComment;
4761 raw_string_ostream ArgCommentStream(ArgComment);
4762 Intrinsic::ID IID = CalledFunc->getIntrinsicID();
4763 Intrinsic::printImmArg(IID, ArgIdx: ArgNo, OS&: ArgCommentStream, ImmArgVal: ConstArg);
4764 if (ArgComment.empty())
4765 return;
4766 Out << "/* " << ArgComment << " */ ";
4767 };
4768 if (HasPrettyPrintedArgs) {
4769 for (unsigned ArgNo = 0, NumArgs = CI->arg_size(); ArgNo < NumArgs;
4770 ++ArgNo) {
4771 Out << LS;
4772 PrintArgComment(ArgNo);
4773 writeParamOperand(Operand: CI->getArgOperand(i: ArgNo), Attrs: PAL.getParamAttrs(ArgNo));
4774 }
4775 } else {
4776 for (unsigned ArgNo = 0, NumArgs = CI->arg_size(); ArgNo < NumArgs;
4777 ++ArgNo) {
4778 Out << LS;
4779 writeParamOperand(Operand: CI->getArgOperand(i: ArgNo), Attrs: PAL.getParamAttrs(ArgNo));
4780 }
4781 }
4782 // Emit an ellipsis if this is a musttail call in a vararg function. This
4783 // is only to aid readability, musttail calls forward varargs by default.
4784 if (CI->isMustTailCall() && CI->getParent() &&
4785 CI->getParent()->getParent() &&
4786 CI->getParent()->getParent()->isVarArg()) {
4787 if (CI->arg_size() > 0)
4788 Out << ", ";
4789 Out << "...";
4790 }
4791
4792 Out << ')';
4793 if (PAL.hasFnAttrs())
4794 Out << " #" << Machine.getAttributeGroupSlot(AS: PAL.getFnAttrs());
4795
4796 writeOperandBundles(Call: CI);
4797 } else if (const auto *II = dyn_cast<InvokeInst>(Val: &I)) {
4798 Operand = II->getCalledOperand();
4799 FunctionType *FTy = II->getFunctionType();
4800 Type *RetTy = FTy->getReturnType();
4801 const AttributeList &PAL = II->getAttributes();
4802
4803 // Print the calling convention being used.
4804 if (II->getCallingConv() != CallingConv::C) {
4805 Out << " ";
4806 printCallingConv(cc: II->getCallingConv(), Out);
4807 }
4808
4809 if (PAL.hasRetAttrs())
4810 Out << ' ' << PAL.getAsString(Index: AttributeList::ReturnIndex);
4811
4812 // Only print addrspace(N) if necessary:
4813 maybePrintCallAddrSpace(Operand, I: &I, Out);
4814
4815 // If possible, print out the short form of the invoke instruction. We can
4816 // only do this if the first argument is a pointer to a nonvararg function,
4817 // and if the return type is not a pointer to a function.
4818 //
4819 Out << ' ';
4820 TypePrinter.print(Ty: FTy->isVarArg() ? FTy : RetTy, OS&: Out);
4821 Out << ' ';
4822 writeOperand(Operand, PrintType: false);
4823 Out << '(';
4824 ListSeparator LS;
4825 for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
4826 Out << LS;
4827 writeParamOperand(Operand: II->getArgOperand(i: op), Attrs: PAL.getParamAttrs(ArgNo: op));
4828 }
4829
4830 Out << ')';
4831 if (PAL.hasFnAttrs())
4832 Out << " #" << Machine.getAttributeGroupSlot(AS: PAL.getFnAttrs());
4833
4834 writeOperandBundles(Call: II);
4835
4836 Out << "\n to ";
4837 writeOperand(Operand: II->getNormalDest(), PrintType: true);
4838 Out << " unwind ";
4839 writeOperand(Operand: II->getUnwindDest(), PrintType: true);
4840 } else if (const auto *CBI = dyn_cast<CallBrInst>(Val: &I)) {
4841 Operand = CBI->getCalledOperand();
4842 FunctionType *FTy = CBI->getFunctionType();
4843 Type *RetTy = FTy->getReturnType();
4844 const AttributeList &PAL = CBI->getAttributes();
4845
4846 // Print the calling convention being used.
4847 if (CBI->getCallingConv() != CallingConv::C) {
4848 Out << " ";
4849 printCallingConv(cc: CBI->getCallingConv(), Out);
4850 }
4851
4852 if (PAL.hasRetAttrs())
4853 Out << ' ' << PAL.getAsString(Index: AttributeList::ReturnIndex);
4854
4855 // If possible, print out the short form of the callbr instruction. We can
4856 // only do this if the first argument is a pointer to a nonvararg function,
4857 // and if the return type is not a pointer to a function.
4858 //
4859 Out << ' ';
4860 TypePrinter.print(Ty: FTy->isVarArg() ? FTy : RetTy, OS&: Out);
4861 Out << ' ';
4862 writeOperand(Operand, PrintType: false);
4863 Out << '(';
4864 ListSeparator ArgLS;
4865 for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
4866 Out << ArgLS;
4867 writeParamOperand(Operand: CBI->getArgOperand(i: op), Attrs: PAL.getParamAttrs(ArgNo: op));
4868 }
4869
4870 Out << ')';
4871 if (PAL.hasFnAttrs())
4872 Out << " #" << Machine.getAttributeGroupSlot(AS: PAL.getFnAttrs());
4873
4874 writeOperandBundles(Call: CBI);
4875
4876 Out << "\n to ";
4877 writeOperand(Operand: CBI->getDefaultDest(), PrintType: true);
4878 Out << " [";
4879 ListSeparator DestLS;
4880 for (const BasicBlock *Dest : CBI->getIndirectDests()) {
4881 Out << DestLS;
4882 writeOperand(Operand: Dest, PrintType: true);
4883 }
4884 Out << ']';
4885 } else if (const auto *AI = dyn_cast<AllocaInst>(Val: &I)) {
4886 Out << ' ';
4887 if (AI->isUsedWithInAlloca())
4888 Out << "inalloca ";
4889 if (AI->isSwiftError())
4890 Out << "swifterror ";
4891 TypePrinter.print(Ty: AI->getAllocatedType(), OS&: Out);
4892
4893 // Explicitly write the array size if the code is broken, if it's an array
4894 // allocation, or if the type is not canonical for scalar allocations. The
4895 // latter case prevents the type from mutating when round-tripping through
4896 // assembly.
4897 if (!AI->getArraySize() || AI->isArrayAllocation() ||
4898 !AI->getArraySize()->getType()->isIntegerTy(BitWidth: 32)) {
4899 Out << ", ";
4900 writeOperand(Operand: AI->getArraySize(), PrintType: true);
4901 }
4902 if (MaybeAlign A = AI->getAlign()) {
4903 Out << ", align " << A->value();
4904 }
4905
4906 printAddressSpace(M: AI->getModule(), AS: AI->getAddressSpace(), OS&: Out,
4907 /*Prefix=*/", ");
4908 } else if (isa<CastInst>(Val: I)) {
4909 if (Operand) {
4910 Out << ' ';
4911 writeOperand(Operand, PrintType: true); // Work with broken code
4912 }
4913 Out << " to ";
4914 TypePrinter.print(Ty: I.getType(), OS&: Out);
4915 } else if (isa<VAArgInst>(Val: I)) {
4916 if (Operand) {
4917 Out << ' ';
4918 writeOperand(Operand, PrintType: true); // Work with broken code
4919 }
4920 Out << ", ";
4921 TypePrinter.print(Ty: I.getType(), OS&: Out);
4922 } else if (Operand) { // Print the normal way.
4923 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Val: &I)) {
4924 Out << ' ';
4925 TypePrinter.print(Ty: GEP->getSourceElementType(), OS&: Out);
4926 Out << ',';
4927 } else if (isa<BitExtractInst>(Val: I) || isa<LoadInst>(Val: I)) {
4928 Out << ' ';
4929 TypePrinter.print(Ty: I.getType(), OS&: Out);
4930 Out << ',';
4931 }
4932
4933 // PrintAllTypes - Instructions who have operands of all the same type
4934 // omit the type from all but the first operand. If the instruction has
4935 // different type operands (for example br), then they are all printed.
4936 bool PrintAllTypes = false;
4937 Type *TheType = Operand->getType();
4938
4939 // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4940 // types.
4941 if (isa<SelectInst>(Val: I) || isa<StoreInst>(Val: I) || isa<ShuffleVectorInst>(Val: I) ||
4942 isa<ReturnInst>(Val: I) || isa<AtomicCmpXchgInst>(Val: I) ||
4943 isa<AtomicRMWInst>(Val: I)) {
4944 PrintAllTypes = true;
4945 } else {
4946 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4947 Operand = I.getOperand(i);
4948 // note that Operand shouldn't be null, but the test helps make dump()
4949 // more tolerant of malformed IR
4950 if (Operand && Operand->getType() != TheType) {
4951 PrintAllTypes = true; // We have differing types! Print them all!
4952 break;
4953 }
4954 }
4955 }
4956
4957 if (!PrintAllTypes) {
4958 Out << ' ';
4959 TypePrinter.print(Ty: TheType, OS&: Out);
4960 }
4961
4962 Out << ' ';
4963 ListSeparator LS;
4964 for (const Value *Op : I.operands()) {
4965 Out << LS;
4966 writeOperand(Operand: Op, PrintType: PrintAllTypes);
4967 }
4968 }
4969
4970 // Print atomic ordering/alignment for memory operations
4971 if (const auto *LI = dyn_cast<LoadInst>(Val: &I)) {
4972 if (LI->isAtomic())
4973 writeAtomic(Context: LI->getContext(), Ordering: LI->getOrdering(), SSID: LI->getSyncScopeID());
4974 if (MaybeAlign A = LI->getAlign())
4975 Out << ", align " << A->value();
4976 } else if (const auto *SI = dyn_cast<StoreInst>(Val: &I)) {
4977 if (SI->isAtomic())
4978 writeAtomic(Context: SI->getContext(), Ordering: SI->getOrdering(), SSID: SI->getSyncScopeID());
4979 if (MaybeAlign A = SI->getAlign())
4980 Out << ", align " << A->value();
4981 } else if (const auto *CXI = dyn_cast<AtomicCmpXchgInst>(Val: &I)) {
4982 writeAtomicCmpXchg(Context: CXI->getContext(), SuccessOrdering: CXI->getSuccessOrdering(),
4983 FailureOrdering: CXI->getFailureOrdering(), SSID: CXI->getSyncScopeID());
4984 Out << ", align " << CXI->getAlign().value();
4985 } else if (const auto *RMWI = dyn_cast<AtomicRMWInst>(Val: &I)) {
4986 writeAtomic(Context: RMWI->getContext(), Ordering: RMWI->getOrdering(),
4987 SSID: RMWI->getSyncScopeID());
4988 Out << ", align " << RMWI->getAlign().value();
4989 } else if (const auto *FI = dyn_cast<FenceInst>(Val: &I)) {
4990 writeAtomic(Context: FI->getContext(), Ordering: FI->getOrdering(), SSID: FI->getSyncScopeID());
4991 } else if (const auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &I)) {
4992 printShuffleMask(Out, Ty: SVI->getType(), Mask: SVI->getShuffleMask());
4993 }
4994
4995 // Print Metadata info.
4996 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4997 I.getAllMetadata(MDs&: InstMD);
4998 printMetadataAttachments(MDs: InstMD, Separator: ", ");
4999
5000 // Print a nice comment.
5001 printInfoComment(V: I);
5002}
5003
5004void AssemblyWriter::printDbgMarker(const DbgMarker &Marker) {
5005 // There's no formal representation of a DbgMarker -- print purely as a
5006 // debugging aid.
5007 for (const DbgRecord &DPR : Marker.StoredDbgRecords) {
5008 printDbgRecord(DR: DPR);
5009 Out << "\n";
5010 }
5011
5012 Out << " DbgMarker -> { ";
5013 printInstruction(I: *Marker.MarkedInstr);
5014 Out << " }";
5015}
5016
5017void AssemblyWriter::printDbgRecord(const DbgRecord &DR) {
5018 if (auto *DVR = dyn_cast<DbgVariableRecord>(Val: &DR))
5019 printDbgVariableRecord(DVR: *DVR);
5020 else if (auto *DLR = dyn_cast<DbgLabelRecord>(Val: &DR))
5021 printDbgLabelRecord(DLR: *DLR);
5022 else
5023 llvm_unreachable("Unexpected DbgRecord kind");
5024}
5025
5026void AssemblyWriter::printDbgVariableRecord(const DbgVariableRecord &DVR) {
5027 auto WriterCtx = getContext();
5028 Out << "#dbg_";
5029 switch (DVR.getType()) {
5030 case DbgVariableRecord::LocationType::Value:
5031 Out << "value";
5032 break;
5033 case DbgVariableRecord::LocationType::Declare:
5034 Out << "declare";
5035 break;
5036 case DbgVariableRecord::LocationType::DeclareValue:
5037 Out << "declare_value";
5038 break;
5039 case DbgVariableRecord::LocationType::Assign:
5040 Out << "assign";
5041 break;
5042 default:
5043 llvm_unreachable(
5044 "Tried to print a DbgVariableRecord with an invalid LocationType!");
5045 }
5046
5047 auto PrintOrNull = [&](Metadata *M) {
5048 if (!M)
5049 Out << "(null)";
5050 else
5051 writeAsOperandInternal(Out, MD: M, WriterCtx, FromValue: true);
5052 };
5053
5054 Out << "(";
5055 PrintOrNull(DVR.getRawLocation());
5056 Out << ", ";
5057 PrintOrNull(DVR.getRawVariable());
5058 Out << ", ";
5059 PrintOrNull(DVR.getRawExpression());
5060 Out << ", ";
5061 if (DVR.isDbgAssign()) {
5062 PrintOrNull(DVR.getRawAssignID());
5063 Out << ", ";
5064 PrintOrNull(DVR.getRawAddress());
5065 Out << ", ";
5066 PrintOrNull(DVR.getRawAddressExpression());
5067 Out << ", ";
5068 }
5069 PrintOrNull(DVR.getDebugLoc().getAsMDNode());
5070 Out << ")";
5071}
5072
5073/// printDbgRecordLine - Print a DbgRecord with indentation and a newline
5074/// character.
5075void AssemblyWriter::printDbgRecordLine(const DbgRecord &DR) {
5076 // Print lengthier indentation to bring out-of-line with instructions.
5077 Out << " ";
5078 printDbgRecord(DR);
5079 Out << '\n';
5080}
5081
5082void AssemblyWriter::printDbgLabelRecord(const DbgLabelRecord &Label) {
5083 auto WriterCtx = getContext();
5084 Out << "#dbg_label(";
5085 writeAsOperandInternal(Out, MD: Label.getRawLabel(), WriterCtx, FromValue: true);
5086 Out << ", ";
5087 writeAsOperandInternal(Out, MD: Label.getDebugLoc(), WriterCtx, FromValue: true);
5088 Out << ")";
5089}
5090
5091void AssemblyWriter::printMetadataAttachments(
5092 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
5093 StringRef Separator) {
5094 if (MDs.empty())
5095 return;
5096
5097 if (MDNames.empty())
5098 MDs[0].second->getContext().getMDKindNames(Result&: MDNames);
5099
5100 auto WriterCtx = getContext();
5101 for (const auto &I : MDs) {
5102 unsigned Kind = I.first;
5103 Out << Separator;
5104 if (Kind < MDNames.size()) {
5105 Out << "!";
5106 printMetadataIdentifier(Name: MDNames[Kind], Out);
5107 } else
5108 Out << "!<unknown kind #" << Kind << ">";
5109 Out << ' ';
5110 writeAsOperandInternal(Out, MD: I.second, WriterCtx);
5111 }
5112}
5113
5114void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
5115 if (AnnotationWriter)
5116 AnnotationWriter->emitMDNodeAnnot(Node, Out);
5117
5118 Out << '!' << Slot << " = ";
5119 printMDNodeBody(MD: Node);
5120 Out << "\n";
5121}
5122
5123void AssemblyWriter::writeAllMDNodes() {
5124 SmallVector<std::pair<unsigned, const MDNode *>, 16> Nodes;
5125 Nodes.reserve(N: Machine.mdn_size());
5126 for (auto &I : llvm::make_range(x: Machine.mdn_begin(), y: Machine.mdn_end()))
5127 Nodes.emplace_back(Args&: I.second, Args: cast<MDNode>(Val: I.first));
5128 llvm::sort(C&: Nodes);
5129
5130 for (auto [Slot, Node] : Nodes)
5131 writeMDNode(Slot, Node);
5132}
5133
5134void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
5135 auto WriterCtx = getContext();
5136 writeMDNodeBodyInternal(Out, Node, Ctx&: WriterCtx);
5137}
5138
5139void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
5140 if (!Attr.isTypeAttribute()) {
5141 Out << Attr.getAsString(InAttrGrp: InAttrGroup);
5142 return;
5143 }
5144
5145 Out << Attribute::getNameFromAttrKind(AttrKind: Attr.getKindAsEnum());
5146 if (Type *Ty = Attr.getValueAsType()) {
5147 Out << '(';
5148 TypePrinter.print(Ty, OS&: Out);
5149 Out << ')';
5150 }
5151}
5152
5153void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
5154 bool InAttrGroup) {
5155 ListSeparator LS(" ");
5156 for (const auto &Attr : AttrSet) {
5157 Out << LS;
5158 writeAttribute(Attr, InAttrGroup);
5159 }
5160}
5161
5162void AssemblyWriter::writeAllAttributeGroups() {
5163 std::vector<std::pair<AttributeSet, unsigned>> asVec;
5164 asVec.resize(new_size: Machine.as_size());
5165
5166 for (auto &I : llvm::make_range(x: Machine.as_begin(), y: Machine.as_end()))
5167 asVec[I.second] = I;
5168
5169 for (const auto &I : asVec)
5170 Out << "attributes #" << I.second << " = { "
5171 << I.first.getAsString(InAttrGrp: true) << " }\n";
5172}
5173
5174void AssemblyWriter::printUseListOrder(const Value *V,
5175 ArrayRef<unsigned> Shuffle) {
5176 if (Machine.getFunction())
5177 Out << " ";
5178
5179 Out << "uselistorder ";
5180 writeOperand(Operand: V, PrintType: true);
5181
5182 assert(Shuffle.size() >= 2 && "Shuffle too small");
5183 Out << ", { " << llvm::interleaved(R: Shuffle) << " }\n";
5184}
5185
5186void AssemblyWriter::printUseLists(const Function *F) {
5187 auto It = UseListOrders.find(Val: F);
5188 if (It == UseListOrders.end())
5189 return;
5190
5191 Out << "\n; uselistorder directives\n";
5192 for (const auto &Pair : It->second)
5193 printUseListOrder(V: Pair.first, Shuffle: Pair.second);
5194}
5195
5196//===----------------------------------------------------------------------===//
5197// External Interface declarations
5198//===----------------------------------------------------------------------===//
5199
5200void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
5201 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
5202 SlotTracker SlotTable(this);
5203 formatted_raw_ostream OS(ROS);
5204 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, IsForDebug,
5205 ShouldPreserveUseListOrder);
5206 W.printFunction(F: this);
5207}
5208
5209void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
5210 bool ShouldPreserveUseListOrder,
5211 bool IsForDebug) const {
5212 SlotTracker SlotTable(this->getParent());
5213 formatted_raw_ostream OS(ROS);
5214 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW, IsForDebug,
5215 ShouldPreserveUseListOrder);
5216 W.printBasicBlock(BB: this);
5217}
5218
5219void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
5220 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
5221 SlotTracker SlotTable(this, /*ShouldTrackMetadataDefinitions=*/true);
5222 formatted_raw_ostream OS(ROS);
5223 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
5224 ShouldPreserveUseListOrder);
5225 W.printModule(M: this);
5226}
5227
5228void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
5229 SlotTracker SlotTable(getParent());
5230 formatted_raw_ostream OS(ROS);
5231 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
5232 W.printNamedMDNode(NMD: this);
5233}
5234
5235void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5236 bool IsForDebug) const {
5237 std::optional<SlotTracker> LocalST;
5238 SlotTracker *SlotTable;
5239 if (auto *ST = MST.getMachine())
5240 SlotTable = ST;
5241 else {
5242 LocalST.emplace(args: getParent());
5243 SlotTable = &*LocalST;
5244 }
5245
5246 formatted_raw_ostream OS(ROS);
5247 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
5248 W.printNamedMDNode(NMD: this);
5249}
5250
5251void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
5252 printLLVMName(OS&: ROS, Name: getName(), Prefix: ComdatPrefix);
5253 ROS << " = comdat ";
5254
5255 switch (getSelectionKind()) {
5256 case Comdat::Any:
5257 ROS << "any";
5258 break;
5259 case Comdat::ExactMatch:
5260 ROS << "exactmatch";
5261 break;
5262 case Comdat::Largest:
5263 ROS << "largest";
5264 break;
5265 case Comdat::NoDeduplicate:
5266 ROS << "nodeduplicate";
5267 break;
5268 case Comdat::SameSize:
5269 ROS << "samesize";
5270 break;
5271 }
5272
5273 ROS << '\n';
5274}
5275
5276void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
5277 TypePrinting TP;
5278 TP.print(Ty: const_cast<Type*>(this), OS);
5279
5280 if (NoDetails)
5281 return;
5282
5283 // If the type is a named struct type, print the body as well.
5284 if (auto *STy = dyn_cast<StructType>(Val: const_cast<Type *>(this)))
5285 if (!STy->isLiteral()) {
5286 OS << " = type ";
5287 TP.printStructBody(STy, OS);
5288 }
5289}
5290
5291void DbgMarker::print(raw_ostream &ROS, bool IsForDebug) const {
5292
5293 ModuleSlotTracker MST(getModuleFromDPI(Marker: this));
5294 print(ROS, MST, IsForDebug);
5295}
5296
5297void DbgVariableRecord::print(raw_ostream &ROS, bool IsForDebug) const {
5298
5299 ModuleSlotTracker MST(getModuleFromDPI(DR: this));
5300 print(ROS, MST, IsForDebug);
5301}
5302
5303void DbgMarker::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5304 bool IsForDebug) const {
5305 formatted_raw_ostream OS(ROS);
5306 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5307 SlotTracker &SlotTable =
5308 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5309 const Function *F = getParent() ? getParent()->getParent() : nullptr;
5310 if (F)
5311 MST.incorporateFunction(F: *F);
5312 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(Marker: this), nullptr, IsForDebug);
5313 W.printDbgMarker(Marker: *this);
5314}
5315
5316void DbgLabelRecord::print(raw_ostream &ROS, bool IsForDebug) const {
5317
5318 ModuleSlotTracker MST(getModuleFromDPI(DR: this));
5319 print(ROS, MST, IsForDebug);
5320}
5321
5322void DbgVariableRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5323 bool IsForDebug) const {
5324 formatted_raw_ostream OS(ROS);
5325 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5326 SlotTracker &SlotTable =
5327 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5328 const Function *F = Marker && Marker->getParent()
5329 ? Marker->getParent()->getParent()
5330 : nullptr;
5331 if (F)
5332 MST.incorporateFunction(F: *F);
5333 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(DR: this), nullptr, IsForDebug);
5334 W.printDbgVariableRecord(DVR: *this);
5335}
5336
5337void DbgLabelRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5338 bool IsForDebug) const {
5339 formatted_raw_ostream OS(ROS);
5340 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5341 SlotTracker &SlotTable =
5342 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5343 const Function *F =
5344 Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
5345 if (F)
5346 MST.incorporateFunction(F: *F);
5347
5348 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(DR: this), nullptr, IsForDebug);
5349 W.printDbgLabelRecord(Label: *this);
5350}
5351
5352void Value::print(raw_ostream &ROS, bool IsForDebug) const {
5353 if (const auto *F = dyn_cast<Function>(Val: this)) {
5354 F->print(ROS, AAW: nullptr, /*ShouldPreserveUseListOrder=*/false, IsForDebug);
5355 return;
5356 }
5357 if (const auto *BB = dyn_cast<BasicBlock>(Val: this)) {
5358 BB->print(ROS, AAW: nullptr, /*ShouldPreserveUseListOrder=*/false, IsForDebug);
5359 return;
5360 }
5361
5362 ModuleSlotTracker MST(getModuleFromVal(V: this));
5363 print(O&: ROS, MST, IsForDebug);
5364}
5365
5366void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5367 bool IsForDebug) const {
5368 formatted_raw_ostream OS(ROS);
5369 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5370 SlotTracker &SlotTable =
5371 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5372 auto IncorporateFunction = [&](const Function *F) {
5373 if (F)
5374 MST.incorporateFunction(F: *F);
5375 };
5376
5377 if (const auto *I = dyn_cast<Instruction>(Val: this)) {
5378 IncorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
5379 AssemblyWriter W(OS, SlotTable, getModuleFromVal(V: I), nullptr, IsForDebug);
5380 W.printInstruction(I: *I);
5381 } else if (const auto *BB = dyn_cast<BasicBlock>(Val: this)) {
5382 IncorporateFunction(BB->getParent());
5383 AssemblyWriter W(OS, SlotTable, getModuleFromVal(V: BB), nullptr, IsForDebug);
5384 W.printBasicBlock(BB);
5385 } else if (const auto *GV = dyn_cast<GlobalValue>(Val: this)) {
5386 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
5387 if (const auto *V = dyn_cast<GlobalVariable>(Val: GV))
5388 W.printGlobal(GV: V);
5389 else if (const auto *F = dyn_cast<Function>(Val: GV))
5390 W.printFunction(F);
5391 else if (const auto *A = dyn_cast<GlobalAlias>(Val: GV))
5392 W.printAlias(GA: A);
5393 else if (const auto *I = dyn_cast<GlobalIFunc>(Val: GV))
5394 W.printIFunc(GI: I);
5395 else
5396 llvm_unreachable("Unknown GlobalValue to print out!");
5397 } else if (const auto *V = dyn_cast<MetadataAsValue>(Val: this)) {
5398 V->getMetadata()->print(OS&: ROS, MST, M: getModuleFromVal(V));
5399 } else if (const auto *C = dyn_cast<Constant>(Val: this)) {
5400 TypePrinting TypePrinter;
5401 TypePrinter.print(Ty: C->getType(), OS);
5402 OS << ' ';
5403 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
5404 writeConstantInternal(Out&: OS, CV: C, WriterCtx);
5405 } else if (isa<InlineAsm>(Val: this) || isa<Argument>(Val: this)) {
5406 this->printAsOperand(O&: OS, /* PrintType */ true, MST);
5407 } else {
5408 llvm_unreachable("Unknown value to print out!");
5409 }
5410}
5411
5412/// Print without a type, skipping the TypePrinting object.
5413///
5414/// \return \c true iff printing was successful.
5415static bool printWithoutType(const Value &V, raw_ostream &O,
5416 SlotTracker *Machine, const Module *M) {
5417 if (V.hasName() || isa<GlobalValue>(Val: V) ||
5418 (!isa<Constant>(Val: V) && !isa<MetadataAsValue>(Val: V))) {
5419 AsmWriterContext WriterCtx(nullptr, Machine, M);
5420 writeAsOperandInternal(Out&: O, V: &V, WriterCtx);
5421 return true;
5422 }
5423 return false;
5424}
5425
5426static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
5427 ModuleSlotTracker &MST) {
5428 TypePrinting TypePrinter(MST.getModule());
5429 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
5430 writeAsOperandInternal(Out&: O, V: &V, WriterCtx, PrintType);
5431}
5432
5433void Value::printAsOperand(raw_ostream &O, bool PrintType,
5434 const Module *M) const {
5435 if (!M)
5436 M = getModuleFromVal(V: this);
5437
5438 if (!PrintType)
5439 if (printWithoutType(V: *this, O, Machine: nullptr, M))
5440 return;
5441
5442 SlotTracker Machine(M);
5443 ModuleSlotTracker MST(Machine, M);
5444 printAsOperandImpl(V: *this, O, PrintType, MST);
5445}
5446
5447void Value::printAsOperand(raw_ostream &O, bool PrintType,
5448 ModuleSlotTracker &MST) const {
5449 if (!PrintType)
5450 if (printWithoutType(V: *this, O, Machine: MST.getMachine(), M: MST.getModule()))
5451 return;
5452
5453 printAsOperandImpl(V: *this, O, PrintType, MST);
5454}
5455
5456/// Recursive version of printMetadataImpl.
5457static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
5458 AsmWriterContext &WriterCtx) {
5459 formatted_raw_ostream OS(ROS);
5460 writeAsOperandInternal(Out&: OS, MD: &MD, WriterCtx, /* FromValue */ true);
5461
5462 auto *N = dyn_cast<MDNode>(Val: &MD);
5463 if (!N || isa<DIExpression>(Val: MD))
5464 return;
5465
5466 OS << " = ";
5467 writeMDNodeBodyInternal(Out&: OS, Node: N, Ctx&: WriterCtx);
5468}
5469
5470namespace {
5471struct MDTreeAsmWriterContext : public AsmWriterContext {
5472 unsigned Level;
5473 // {Level, Printed string}
5474 using EntryTy = std::pair<unsigned, std::string>;
5475 SmallVector<EntryTy, 4> Buffer;
5476
5477 // Used to break the cycle in case there is any.
5478 SmallPtrSet<const Metadata *, 4> Visited;
5479
5480 raw_ostream &MainOS;
5481
5482 MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
5483 const ModuleSlotTracker *MST, raw_ostream &OS,
5484 const Metadata *InitMD)
5485 : AsmWriterContext(TP, ST, M, MST), Level(0U), Visited({InitMD}),
5486 MainOS(OS) {}
5487
5488 void onWriteMetadataAsOperand(const Metadata *MD) override {
5489 if (!Visited.insert(Ptr: MD).second)
5490 return;
5491
5492 std::string Str;
5493 raw_string_ostream SS(Str);
5494 ++Level;
5495 // A placeholder entry to memorize the correct
5496 // position in buffer.
5497 Buffer.emplace_back(Args: std::make_pair(x&: Level, y: ""));
5498 unsigned InsertIdx = Buffer.size() - 1;
5499
5500 printMetadataImplRec(ROS&: SS, MD: *MD, WriterCtx&: *this);
5501 Buffer[InsertIdx].second = std::move(SS.str());
5502 --Level;
5503 }
5504
5505 ~MDTreeAsmWriterContext() override {
5506 for (const auto &Entry : Buffer) {
5507 MainOS << "\n";
5508 unsigned NumIndent = Entry.first * 2U;
5509 MainOS.indent(NumSpaces: NumIndent) << Entry.second;
5510 }
5511 }
5512};
5513} // end anonymous namespace
5514
5515static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
5516 ModuleSlotTracker &MST, const Module *M,
5517 bool OnlyAsOperand, bool PrintAsTree = false) {
5518 formatted_raw_ostream OS(ROS);
5519
5520 TypePrinting TypePrinter(M);
5521
5522 std::unique_ptr<AsmWriterContext> WriterCtx;
5523 if (PrintAsTree && !OnlyAsOperand)
5524 WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
5525 args: &TypePrinter, args: MST.getMachine(), args&: M, args: &MST, args&: OS, args: &MD);
5526 else
5527 WriterCtx = std::make_unique<AsmWriterContext>(args: &TypePrinter,
5528 args: MST.getMachine(), args&: M, args: &MST);
5529
5530 writeAsOperandInternal(Out&: OS, MD: &MD, WriterCtx&: *WriterCtx, /* FromValue */ true);
5531
5532 auto *N = dyn_cast<MDNode>(Val: &MD);
5533 if (OnlyAsOperand || !N || isa<DIExpression>(Val: MD))
5534 return;
5535
5536 OS << " = ";
5537 writeMDNodeBodyInternal(Out&: OS, Node: N, Ctx&: *WriterCtx);
5538}
5539
5540void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
5541 ModuleSlotTracker MST(M);
5542 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ true);
5543}
5544
5545void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
5546 const Module *M) const {
5547 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ true);
5548}
5549
5550void Metadata::print(raw_ostream &OS, const Module *M,
5551 bool /*IsForDebug*/) const {
5552 ModuleSlotTracker MST(M);
5553 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ false);
5554}
5555
5556void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
5557 const Module *M, bool /*IsForDebug*/) const {
5558 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ false);
5559}
5560
5561void MDNode::printTree(raw_ostream &OS, const Module *M) const {
5562 ModuleSlotTracker MST(M);
5563 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ false,
5564 /*PrintAsTree=*/true);
5565}
5566
5567void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
5568 const Module *M) const {
5569 printMetadataImpl(ROS&: OS, MD: *this, MST, M, /* OnlyAsOperand */ false,
5570 /*PrintAsTree=*/true);
5571}
5572
5573void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
5574 SlotTracker SlotTable(this);
5575 formatted_raw_ostream OS(ROS);
5576 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
5577 W.printModuleSummaryIndex();
5578}
5579
5580void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L) const {
5581 SlotTracker *ST = MachineStorage.get();
5582 if (!ST)
5583 return;
5584
5585 for (auto &I : llvm::make_range(x: ST->mdn_begin(), y: ST->mdn_end()))
5586 L.push_back(Elt: std::make_pair(x&: I.second, y&: I.first));
5587}
5588
5589#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5590// Value::dump - allow easy printing of Values from the debugger.
5591LLVM_DUMP_METHOD
5592void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5593
5594// Value::dump - allow easy printing of Values from the debugger.
5595LLVM_DUMP_METHOD
5596void DbgMarker::dump() const {
5597 print(dbgs(), /*IsForDebug=*/true);
5598 dbgs() << '\n';
5599}
5600
5601// Value::dump - allow easy printing of Values from the debugger.
5602LLVM_DUMP_METHOD
5603void DbgRecord::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5604
5605// Type::dump - allow easy printing of Types from the debugger.
5606LLVM_DUMP_METHOD
5607void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5608
5609// Module::dump() - Allow printing of Modules from the debugger.
5610LLVM_DUMP_METHOD
5611void Module::dump() const {
5612 print(dbgs(), nullptr,
5613 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
5614}
5615
5616// Allow printing of Comdats from the debugger.
5617LLVM_DUMP_METHOD
5618void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5619
5620// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
5621LLVM_DUMP_METHOD
5622void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5623
5624LLVM_DUMP_METHOD
5625void Metadata::dump() const { dump(nullptr); }
5626
5627LLVM_DUMP_METHOD
5628void Metadata::dump(const Module *M) const {
5629 print(dbgs(), M, /*IsForDebug=*/true);
5630 dbgs() << '\n';
5631}
5632
5633LLVM_DUMP_METHOD
5634void MDNode::dumpTree() const { dumpTree(nullptr); }
5635
5636LLVM_DUMP_METHOD
5637void MDNode::dumpTree(const Module *M) const {
5638 printTree(dbgs(), M);
5639 dbgs() << '\n';
5640}
5641
5642// Allow printing of ModuleSummaryIndex from the debugger.
5643LLVM_DUMP_METHOD
5644void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5645#endif
5646