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