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