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