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