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