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