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