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