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