[LLVM][Alignment] Introduce Alignment In Attributes
[llvm-core.git] / lib / IR / AsmWriter.cpp
blob2462e933ba4a8c1c84826ac592172dfa61ba9c3b
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.
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.
16 //===----------------------------------------------------------------------===//
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/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/Argument.h"
34 #include "llvm/IR/AssemblyAnnotationWriter.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Comdat.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfoMetadata.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalIFunc.h"
47 #include "llvm/IR/GlobalIndirectSymbol.h"
48 #include "llvm/IR/GlobalObject.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/IRPrintingPasses.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSlotTracker.h"
60 #include "llvm/IR/ModuleSummaryIndex.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/Statepoint.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/TypeFinder.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/UseListOrder.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/Support/AtomicOrdering.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/Format.h"
75 #include "llvm/Support/FormattedStream.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <cctype>
80 #include <cstddef>
81 #include <cstdint>
82 #include <iterator>
83 #include <memory>
84 #include <string>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
89 using namespace llvm;
91 // Make virtual table appear in this compilation unit.
92 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
94 //===----------------------------------------------------------------------===//
95 // Helper Functions
96 //===----------------------------------------------------------------------===//
98 namespace {
100 struct OrderMap {
101 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
103 unsigned size() const { return IDs.size(); }
104 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
106 std::pair<unsigned, bool> lookup(const Value *V) const {
107 return IDs.lookup(V);
110 void index(const Value *V) {
111 // Explicitly sequence get-size and insert-value operations to avoid UB.
112 unsigned ID = IDs.size() + 1;
113 IDs[V].first = ID;
117 } // end anonymous namespace
119 static void orderValue(const Value *V, OrderMap &OM) {
120 if (OM.lookup(V).first)
121 return;
123 if (const Constant *C = dyn_cast<Constant>(V))
124 if (C->getNumOperands() && !isa<GlobalValue>(C))
125 for (const Value *Op : C->operands())
126 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
127 orderValue(Op, OM);
129 // Note: we cannot cache this lookup above, since inserting into the map
130 // changes the map's size, and thus affects the other IDs.
131 OM.index(V);
134 static OrderMap orderModule(const Module *M) {
135 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
136 // and ValueEnumerator::incorporateFunction().
137 OrderMap OM;
139 for (const GlobalVariable &G : M->globals()) {
140 if (G.hasInitializer())
141 if (!isa<GlobalValue>(G.getInitializer()))
142 orderValue(G.getInitializer(), OM);
143 orderValue(&G, OM);
145 for (const GlobalAlias &A : M->aliases()) {
146 if (!isa<GlobalValue>(A.getAliasee()))
147 orderValue(A.getAliasee(), OM);
148 orderValue(&A, OM);
150 for (const GlobalIFunc &I : M->ifuncs()) {
151 if (!isa<GlobalValue>(I.getResolver()))
152 orderValue(I.getResolver(), OM);
153 orderValue(&I, OM);
155 for (const Function &F : *M) {
156 for (const Use &U : F.operands())
157 if (!isa<GlobalValue>(U.get()))
158 orderValue(U.get(), OM);
160 orderValue(&F, OM);
162 if (F.isDeclaration())
163 continue;
165 for (const Argument &A : F.args())
166 orderValue(&A, OM);
167 for (const BasicBlock &BB : F) {
168 orderValue(&BB, OM);
169 for (const Instruction &I : BB) {
170 for (const Value *Op : I.operands())
171 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
172 isa<InlineAsm>(*Op))
173 orderValue(Op, OM);
174 orderValue(&I, OM);
178 return OM;
181 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
182 unsigned ID, const OrderMap &OM,
183 UseListOrderStack &Stack) {
184 // Predict use-list order for this one.
185 using Entry = std::pair<const Use *, unsigned>;
186 SmallVector<Entry, 64> List;
187 for (const Use &U : V->uses())
188 // Check if this user will be serialized.
189 if (OM.lookup(U.getUser()).first)
190 List.push_back(std::make_pair(&U, List.size()));
192 if (List.size() < 2)
193 // We may have lost some users.
194 return;
196 bool GetsReversed =
197 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
198 if (auto *BA = dyn_cast<BlockAddress>(V))
199 ID = OM.lookup(BA->getBasicBlock()).first;
200 llvm::sort(List, [&](const Entry &L, const Entry &R) {
201 const Use *LU = L.first;
202 const Use *RU = R.first;
203 if (LU == RU)
204 return false;
206 auto LID = OM.lookup(LU->getUser()).first;
207 auto RID = OM.lookup(RU->getUser()).first;
209 // If ID is 4, then expect: 7 6 5 1 2 3.
210 if (LID < RID) {
211 if (GetsReversed)
212 if (RID <= ID)
213 return true;
214 return false;
216 if (RID < LID) {
217 if (GetsReversed)
218 if (LID <= ID)
219 return false;
220 return true;
223 // LID and RID are equal, so we have different operands of the same user.
224 // Assume operands are added in order for all instructions.
225 if (GetsReversed)
226 if (LID <= ID)
227 return LU->getOperandNo() < RU->getOperandNo();
228 return LU->getOperandNo() > RU->getOperandNo();
231 if (std::is_sorted(
232 List.begin(), List.end(),
233 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
234 // Order is already correct.
235 return;
237 // Store the shuffle.
238 Stack.emplace_back(V, F, List.size());
239 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
240 for (size_t I = 0, E = List.size(); I != E; ++I)
241 Stack.back().Shuffle[I] = List[I].second;
244 static void predictValueUseListOrder(const Value *V, const Function *F,
245 OrderMap &OM, UseListOrderStack &Stack) {
246 auto &IDPair = OM[V];
247 assert(IDPair.first && "Unmapped value");
248 if (IDPair.second)
249 // Already predicted.
250 return;
252 // Do the actual prediction.
253 IDPair.second = true;
254 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
255 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
257 // Recursive descent into constants.
258 if (const Constant *C = dyn_cast<Constant>(V))
259 if (C->getNumOperands()) // Visit GlobalValues.
260 for (const Value *Op : C->operands())
261 if (isa<Constant>(Op)) // Visit GlobalValues.
262 predictValueUseListOrder(Op, F, OM, Stack);
265 static UseListOrderStack predictUseListOrder(const Module *M) {
266 OrderMap OM = orderModule(M);
268 // Use-list orders need to be serialized after all the users have been added
269 // to a value, or else the shuffles will be incomplete. Store them per
270 // function in a stack.
272 // Aside from function order, the order of values doesn't matter much here.
273 UseListOrderStack Stack;
275 // We want to visit the functions backward now so we can list function-local
276 // constants in the last Function they're used in. Module-level constants
277 // have already been visited above.
278 for (const Function &F : make_range(M->rbegin(), M->rend())) {
279 if (F.isDeclaration())
280 continue;
281 for (const BasicBlock &BB : F)
282 predictValueUseListOrder(&BB, &F, OM, Stack);
283 for (const Argument &A : F.args())
284 predictValueUseListOrder(&A, &F, OM, Stack);
285 for (const BasicBlock &BB : F)
286 for (const Instruction &I : BB)
287 for (const Value *Op : I.operands())
288 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
289 predictValueUseListOrder(Op, &F, OM, Stack);
290 for (const BasicBlock &BB : F)
291 for (const Instruction &I : BB)
292 predictValueUseListOrder(&I, &F, OM, Stack);
295 // Visit globals last.
296 for (const GlobalVariable &G : M->globals())
297 predictValueUseListOrder(&G, nullptr, OM, Stack);
298 for (const Function &F : *M)
299 predictValueUseListOrder(&F, nullptr, OM, Stack);
300 for (const GlobalAlias &A : M->aliases())
301 predictValueUseListOrder(&A, nullptr, OM, Stack);
302 for (const GlobalIFunc &I : M->ifuncs())
303 predictValueUseListOrder(&I, nullptr, OM, Stack);
304 for (const GlobalVariable &G : M->globals())
305 if (G.hasInitializer())
306 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
307 for (const GlobalAlias &A : M->aliases())
308 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
309 for (const GlobalIFunc &I : M->ifuncs())
310 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
311 for (const Function &F : *M)
312 for (const Use &U : F.operands())
313 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
315 return Stack;
318 static const Module *getModuleFromVal(const Value *V) {
319 if (const Argument *MA = dyn_cast<Argument>(V))
320 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
322 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
323 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
325 if (const Instruction *I = dyn_cast<Instruction>(V)) {
326 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
327 return M ? M->getParent() : nullptr;
330 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
331 return GV->getParent();
333 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
334 for (const User *U : MAV->users())
335 if (isa<Instruction>(U))
336 if (const Module *M = getModuleFromVal(U))
337 return M;
338 return nullptr;
341 return nullptr;
344 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
345 switch (cc) {
346 default: Out << "cc" << cc; break;
347 case CallingConv::Fast: Out << "fastcc"; break;
348 case CallingConv::Cold: Out << "coldcc"; break;
349 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
350 case CallingConv::AnyReg: Out << "anyregcc"; break;
351 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
352 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
353 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
354 case CallingConv::GHC: Out << "ghccc"; break;
355 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
356 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
357 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
358 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
359 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
360 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
361 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
362 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
363 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
364 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
365 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
366 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
367 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
368 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
369 case CallingConv::PTX_Device: Out << "ptx_device"; break;
370 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
371 case CallingConv::Win64: Out << "win64cc"; break;
372 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
373 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
374 case CallingConv::Swift: Out << "swiftcc"; break;
375 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
376 case CallingConv::HHVM: Out << "hhvmcc"; break;
377 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
378 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
379 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
380 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
381 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
382 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
383 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
384 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
385 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
389 enum PrefixType {
390 GlobalPrefix,
391 ComdatPrefix,
392 LabelPrefix,
393 LocalPrefix,
394 NoPrefix
397 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
398 assert(!Name.empty() && "Cannot get empty name!");
400 // Scan the name to see if it needs quotes first.
401 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
402 if (!NeedsQuotes) {
403 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
404 // By making this unsigned, the value passed in to isalnum will always be
405 // in the range 0-255. This is important when building with MSVC because
406 // its implementation will assert. This situation can arise when dealing
407 // with UTF-8 multibyte characters.
408 unsigned char C = Name[i];
409 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
410 C != '_') {
411 NeedsQuotes = true;
412 break;
417 // If we didn't need any quotes, just write out the name in one blast.
418 if (!NeedsQuotes) {
419 OS << Name;
420 return;
423 // Okay, we need quotes. Output the quotes and escape any scary characters as
424 // needed.
425 OS << '"';
426 printEscapedString(Name, OS);
427 OS << '"';
430 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
431 /// (if the string only contains simple characters) or is surrounded with ""'s
432 /// (if it has special chars in it). Print it out.
433 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
434 switch (Prefix) {
435 case NoPrefix:
436 break;
437 case GlobalPrefix:
438 OS << '@';
439 break;
440 case ComdatPrefix:
441 OS << '$';
442 break;
443 case LabelPrefix:
444 break;
445 case LocalPrefix:
446 OS << '%';
447 break;
449 printLLVMNameWithoutPrefix(OS, Name);
452 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
453 /// (if the string only contains simple characters) or is surrounded with ""'s
454 /// (if it has special chars in it). Print it out.
455 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
456 PrintLLVMName(OS, V->getName(),
457 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
460 namespace {
462 class TypePrinting {
463 public:
464 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
466 TypePrinting(const TypePrinting &) = delete;
467 TypePrinting &operator=(const TypePrinting &) = delete;
469 /// The named types that are used by the current module.
470 TypeFinder &getNamedTypes();
472 /// The numbered types, number to type mapping.
473 std::vector<StructType *> &getNumberedTypes();
475 bool empty();
477 void print(Type *Ty, raw_ostream &OS);
479 void printStructBody(StructType *Ty, raw_ostream &OS);
481 private:
482 void incorporateTypes();
484 /// A module to process lazily when needed. Set to nullptr as soon as used.
485 const Module *DeferredM;
487 TypeFinder NamedTypes;
489 // The numbered types, along with their value.
490 DenseMap<StructType *, unsigned> Type2Number;
492 std::vector<StructType *> NumberedTypes;
495 } // end anonymous namespace
497 TypeFinder &TypePrinting::getNamedTypes() {
498 incorporateTypes();
499 return NamedTypes;
502 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
503 incorporateTypes();
505 // We know all the numbers that each type is used and we know that it is a
506 // dense assignment. Convert the map to an index table, if it's not done
507 // already (judging from the sizes):
508 if (NumberedTypes.size() == Type2Number.size())
509 return NumberedTypes;
511 NumberedTypes.resize(Type2Number.size());
512 for (const auto &P : Type2Number) {
513 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
514 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
515 NumberedTypes[P.second] = P.first;
517 return NumberedTypes;
520 bool TypePrinting::empty() {
521 incorporateTypes();
522 return NamedTypes.empty() && Type2Number.empty();
525 void TypePrinting::incorporateTypes() {
526 if (!DeferredM)
527 return;
529 NamedTypes.run(*DeferredM, false);
530 DeferredM = nullptr;
532 // The list of struct types we got back includes all the struct types, split
533 // the unnamed ones out to a numbering and remove the anonymous structs.
534 unsigned NextNumber = 0;
536 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
537 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
538 StructType *STy = *I;
540 // Ignore anonymous types.
541 if (STy->isLiteral())
542 continue;
544 if (STy->getName().empty())
545 Type2Number[STy] = NextNumber++;
546 else
547 *NextToUse++ = STy;
550 NamedTypes.erase(NextToUse, NamedTypes.end());
553 /// Write the specified type to the specified raw_ostream, making use of type
554 /// names or up references to shorten the type name where possible.
555 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
556 switch (Ty->getTypeID()) {
557 case Type::VoidTyID: OS << "void"; return;
558 case Type::HalfTyID: OS << "half"; return;
559 case Type::FloatTyID: OS << "float"; return;
560 case Type::DoubleTyID: OS << "double"; return;
561 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
562 case Type::FP128TyID: OS << "fp128"; return;
563 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
564 case Type::LabelTyID: OS << "label"; return;
565 case Type::MetadataTyID: OS << "metadata"; return;
566 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
567 case Type::TokenTyID: OS << "token"; return;
568 case Type::IntegerTyID:
569 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
570 return;
572 case Type::FunctionTyID: {
573 FunctionType *FTy = cast<FunctionType>(Ty);
574 print(FTy->getReturnType(), OS);
575 OS << " (";
576 for (FunctionType::param_iterator I = FTy->param_begin(),
577 E = FTy->param_end(); I != E; ++I) {
578 if (I != FTy->param_begin())
579 OS << ", ";
580 print(*I, OS);
582 if (FTy->isVarArg()) {
583 if (FTy->getNumParams()) OS << ", ";
584 OS << "...";
586 OS << ')';
587 return;
589 case Type::StructTyID: {
590 StructType *STy = cast<StructType>(Ty);
592 if (STy->isLiteral())
593 return printStructBody(STy, OS);
595 if (!STy->getName().empty())
596 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
598 incorporateTypes();
599 const auto I = Type2Number.find(STy);
600 if (I != Type2Number.end())
601 OS << '%' << I->second;
602 else // Not enumerated, print the hex address.
603 OS << "%\"type " << STy << '\"';
604 return;
606 case Type::PointerTyID: {
607 PointerType *PTy = cast<PointerType>(Ty);
608 print(PTy->getElementType(), OS);
609 if (unsigned AddressSpace = PTy->getAddressSpace())
610 OS << " addrspace(" << AddressSpace << ')';
611 OS << '*';
612 return;
614 case Type::ArrayTyID: {
615 ArrayType *ATy = cast<ArrayType>(Ty);
616 OS << '[' << ATy->getNumElements() << " x ";
617 print(ATy->getElementType(), OS);
618 OS << ']';
619 return;
621 case Type::VectorTyID: {
622 VectorType *PTy = cast<VectorType>(Ty);
623 OS << "<";
624 if (PTy->isScalable())
625 OS << "vscale x ";
626 OS << PTy->getNumElements() << " x ";
627 print(PTy->getElementType(), OS);
628 OS << '>';
629 return;
632 llvm_unreachable("Invalid TypeID");
635 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
636 if (STy->isOpaque()) {
637 OS << "opaque";
638 return;
641 if (STy->isPacked())
642 OS << '<';
644 if (STy->getNumElements() == 0) {
645 OS << "{}";
646 } else {
647 StructType::element_iterator I = STy->element_begin();
648 OS << "{ ";
649 print(*I++, OS);
650 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
651 OS << ", ";
652 print(*I, OS);
655 OS << " }";
657 if (STy->isPacked())
658 OS << '>';
661 namespace llvm {
663 //===----------------------------------------------------------------------===//
664 // SlotTracker Class: Enumerate slot numbers for unnamed values
665 //===----------------------------------------------------------------------===//
666 /// This class provides computation of slot numbers for LLVM Assembly writing.
668 class SlotTracker {
669 public:
670 /// ValueMap - A mapping of Values to slot numbers.
671 using ValueMap = DenseMap<const Value *, unsigned>;
673 private:
674 /// TheModule - The module for which we are holding slot numbers.
675 const Module* TheModule;
677 /// TheFunction - The function for which we are holding slot numbers.
678 const Function* TheFunction = nullptr;
679 bool FunctionProcessed = false;
680 bool ShouldInitializeAllMetadata;
682 /// The summary index for which we are holding slot numbers.
683 const ModuleSummaryIndex *TheIndex = nullptr;
685 /// mMap - The slot map for the module level data.
686 ValueMap mMap;
687 unsigned mNext = 0;
689 /// fMap - The slot map for the function level data.
690 ValueMap fMap;
691 unsigned fNext = 0;
693 /// mdnMap - Map for MDNodes.
694 DenseMap<const MDNode*, unsigned> mdnMap;
695 unsigned mdnNext = 0;
697 /// asMap - The slot map for attribute sets.
698 DenseMap<AttributeSet, unsigned> asMap;
699 unsigned asNext = 0;
701 /// ModulePathMap - The slot map for Module paths used in the summary index.
702 StringMap<unsigned> ModulePathMap;
703 unsigned ModulePathNext = 0;
705 /// GUIDMap - The slot map for GUIDs used in the summary index.
706 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
707 unsigned GUIDNext = 0;
709 /// TypeIdMap - The slot map for type ids used in the summary index.
710 StringMap<unsigned> TypeIdMap;
711 unsigned TypeIdNext = 0;
713 public:
714 /// Construct from a module.
716 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
717 /// functions, giving correct numbering for metadata referenced only from
718 /// within a function (even if no functions have been initialized).
719 explicit SlotTracker(const Module *M,
720 bool ShouldInitializeAllMetadata = false);
722 /// Construct from a function, starting out in incorp state.
724 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
725 /// functions, giving correct numbering for metadata referenced only from
726 /// within a function (even if no functions have been initialized).
727 explicit SlotTracker(const Function *F,
728 bool ShouldInitializeAllMetadata = false);
730 /// Construct from a module summary index.
731 explicit SlotTracker(const ModuleSummaryIndex *Index);
733 SlotTracker(const SlotTracker &) = delete;
734 SlotTracker &operator=(const SlotTracker &) = delete;
736 /// Return the slot number of the specified value in it's type
737 /// plane. If something is not in the SlotTracker, return -1.
738 int getLocalSlot(const Value *V);
739 int getGlobalSlot(const GlobalValue *V);
740 int getMetadataSlot(const MDNode *N);
741 int getAttributeGroupSlot(AttributeSet AS);
742 int getModulePathSlot(StringRef Path);
743 int getGUIDSlot(GlobalValue::GUID GUID);
744 int getTypeIdSlot(StringRef Id);
746 /// If you'd like to deal with a function instead of just a module, use
747 /// this method to get its data into the SlotTracker.
748 void incorporateFunction(const Function *F) {
749 TheFunction = F;
750 FunctionProcessed = false;
753 const Function *getFunction() const { return TheFunction; }
755 /// After calling incorporateFunction, use this method to remove the
756 /// most recently incorporated function from the SlotTracker. This
757 /// will reset the state of the machine back to just the module contents.
758 void purgeFunction();
760 /// MDNode map iterators.
761 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
763 mdn_iterator mdn_begin() { return mdnMap.begin(); }
764 mdn_iterator mdn_end() { return mdnMap.end(); }
765 unsigned mdn_size() const { return mdnMap.size(); }
766 bool mdn_empty() const { return mdnMap.empty(); }
768 /// AttributeSet map iterators.
769 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
771 as_iterator as_begin() { return asMap.begin(); }
772 as_iterator as_end() { return asMap.end(); }
773 unsigned as_size() const { return asMap.size(); }
774 bool as_empty() const { return asMap.empty(); }
776 /// GUID map iterators.
777 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
779 /// These functions do the actual initialization.
780 inline void initializeIfNeeded();
781 void initializeIndexIfNeeded();
783 // Implementation Details
784 private:
785 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
786 void CreateModuleSlot(const GlobalValue *V);
788 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
789 void CreateMetadataSlot(const MDNode *N);
791 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
792 void CreateFunctionSlot(const Value *V);
794 /// Insert the specified AttributeSet into the slot table.
795 void CreateAttributeSetSlot(AttributeSet AS);
797 inline void CreateModulePathSlot(StringRef Path);
798 void CreateGUIDSlot(GlobalValue::GUID GUID);
799 void CreateTypeIdSlot(StringRef Id);
801 /// Add all of the module level global variables (and their initializers)
802 /// and function declarations, but not the contents of those functions.
803 void processModule();
804 void processIndex();
806 /// Add all of the functions arguments, basic blocks, and instructions.
807 void processFunction();
809 /// Add the metadata directly attached to a GlobalObject.
810 void processGlobalObjectMetadata(const GlobalObject &GO);
812 /// Add all of the metadata from a function.
813 void processFunctionMetadata(const Function &F);
815 /// Add all of the metadata from an instruction.
816 void processInstructionMetadata(const Instruction &I);
819 } // end namespace llvm
821 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
822 const Function *F)
823 : M(M), F(F), Machine(&Machine) {}
825 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
826 bool ShouldInitializeAllMetadata)
827 : ShouldCreateStorage(M),
828 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
830 ModuleSlotTracker::~ModuleSlotTracker() = default;
832 SlotTracker *ModuleSlotTracker::getMachine() {
833 if (!ShouldCreateStorage)
834 return Machine;
836 ShouldCreateStorage = false;
837 MachineStorage =
838 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
839 Machine = MachineStorage.get();
840 return Machine;
843 void ModuleSlotTracker::incorporateFunction(const Function &F) {
844 // Using getMachine() may lazily create the slot tracker.
845 if (!getMachine())
846 return;
848 // Nothing to do if this is the right function already.
849 if (this->F == &F)
850 return;
851 if (this->F)
852 Machine->purgeFunction();
853 Machine->incorporateFunction(&F);
854 this->F = &F;
857 int ModuleSlotTracker::getLocalSlot(const Value *V) {
858 assert(F && "No function incorporated");
859 return Machine->getLocalSlot(V);
862 static SlotTracker *createSlotTracker(const Value *V) {
863 if (const Argument *FA = dyn_cast<Argument>(V))
864 return new SlotTracker(FA->getParent());
866 if (const Instruction *I = dyn_cast<Instruction>(V))
867 if (I->getParent())
868 return new SlotTracker(I->getParent()->getParent());
870 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
871 return new SlotTracker(BB->getParent());
873 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
874 return new SlotTracker(GV->getParent());
876 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
877 return new SlotTracker(GA->getParent());
879 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
880 return new SlotTracker(GIF->getParent());
882 if (const Function *Func = dyn_cast<Function>(V))
883 return new SlotTracker(Func);
885 return nullptr;
888 #if 0
889 #define ST_DEBUG(X) dbgs() << X
890 #else
891 #define ST_DEBUG(X)
892 #endif
894 // Module level constructor. Causes the contents of the Module (sans functions)
895 // to be added to the slot table.
896 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
897 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
899 // Function level constructor. Causes the contents of the Module and the one
900 // function provided to be added to the slot table.
901 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
902 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
903 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
905 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
906 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
908 inline void SlotTracker::initializeIfNeeded() {
909 if (TheModule) {
910 processModule();
911 TheModule = nullptr; ///< Prevent re-processing next time we're called.
914 if (TheFunction && !FunctionProcessed)
915 processFunction();
918 void SlotTracker::initializeIndexIfNeeded() {
919 if (!TheIndex)
920 return;
921 processIndex();
922 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
925 // Iterate through all the global variables, functions, and global
926 // variable initializers and create slots for them.
927 void SlotTracker::processModule() {
928 ST_DEBUG("begin processModule!\n");
930 // Add all of the unnamed global variables to the value table.
931 for (const GlobalVariable &Var : TheModule->globals()) {
932 if (!Var.hasName())
933 CreateModuleSlot(&Var);
934 processGlobalObjectMetadata(Var);
935 auto Attrs = Var.getAttributes();
936 if (Attrs.hasAttributes())
937 CreateAttributeSetSlot(Attrs);
940 for (const GlobalAlias &A : TheModule->aliases()) {
941 if (!A.hasName())
942 CreateModuleSlot(&A);
945 for (const GlobalIFunc &I : TheModule->ifuncs()) {
946 if (!I.hasName())
947 CreateModuleSlot(&I);
950 // Add metadata used by named metadata.
951 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
952 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
953 CreateMetadataSlot(NMD.getOperand(i));
956 for (const Function &F : *TheModule) {
957 if (!F.hasName())
958 // Add all the unnamed functions to the table.
959 CreateModuleSlot(&F);
961 if (ShouldInitializeAllMetadata)
962 processFunctionMetadata(F);
964 // Add all the function attributes to the table.
965 // FIXME: Add attributes of other objects?
966 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
967 if (FnAttrs.hasAttributes())
968 CreateAttributeSetSlot(FnAttrs);
971 ST_DEBUG("end processModule!\n");
974 // Process the arguments, basic blocks, and instructions of a function.
975 void SlotTracker::processFunction() {
976 ST_DEBUG("begin processFunction!\n");
977 fNext = 0;
979 // Process function metadata if it wasn't hit at the module-level.
980 if (!ShouldInitializeAllMetadata)
981 processFunctionMetadata(*TheFunction);
983 // Add all the function arguments with no names.
984 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
985 AE = TheFunction->arg_end(); AI != AE; ++AI)
986 if (!AI->hasName())
987 CreateFunctionSlot(&*AI);
989 ST_DEBUG("Inserting Instructions:\n");
991 // Add all of the basic blocks and instructions with no names.
992 for (auto &BB : *TheFunction) {
993 if (!BB.hasName())
994 CreateFunctionSlot(&BB);
996 for (auto &I : BB) {
997 if (!I.getType()->isVoidTy() && !I.hasName())
998 CreateFunctionSlot(&I);
1000 // We allow direct calls to any llvm.foo function here, because the
1001 // target may not be linked into the optimizer.
1002 if (const auto *Call = dyn_cast<CallBase>(&I)) {
1003 // Add all the call attributes to the table.
1004 AttributeSet Attrs = Call->getAttributes().getFnAttributes();
1005 if (Attrs.hasAttributes())
1006 CreateAttributeSetSlot(Attrs);
1011 FunctionProcessed = true;
1013 ST_DEBUG("end processFunction!\n");
1016 // Iterate through all the GUID in the index and create slots for them.
1017 void SlotTracker::processIndex() {
1018 ST_DEBUG("begin processIndex!\n");
1019 assert(TheIndex);
1021 // The first block of slots are just the module ids, which start at 0 and are
1022 // assigned consecutively. Since the StringMap iteration order isn't
1023 // guaranteed, use a std::map to order by module ID before assigning slots.
1024 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1025 for (auto &ModPath : TheIndex->modulePaths())
1026 ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1027 for (auto &ModPair : ModuleIdToPathMap)
1028 CreateModulePathSlot(ModPair.second);
1030 // Start numbering the GUIDs after the module ids.
1031 GUIDNext = ModulePathNext;
1033 for (auto &GlobalList : *TheIndex)
1034 CreateGUIDSlot(GlobalList.first);
1036 // Start numbering the TypeIds after the GUIDs.
1037 TypeIdNext = GUIDNext;
1039 for (auto TidIter = TheIndex->typeIds().begin();
1040 TidIter != TheIndex->typeIds().end(); TidIter++)
1041 CreateTypeIdSlot(TidIter->second.first);
1043 for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1044 CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1046 ST_DEBUG("end processIndex!\n");
1049 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1050 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1051 GO.getAllMetadata(MDs);
1052 for (auto &MD : MDs)
1053 CreateMetadataSlot(MD.second);
1056 void SlotTracker::processFunctionMetadata(const Function &F) {
1057 processGlobalObjectMetadata(F);
1058 for (auto &BB : F) {
1059 for (auto &I : BB)
1060 processInstructionMetadata(I);
1064 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1065 // Process metadata used directly by intrinsics.
1066 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1067 if (Function *F = CI->getCalledFunction())
1068 if (F->isIntrinsic())
1069 for (auto &Op : I.operands())
1070 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1071 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1072 CreateMetadataSlot(N);
1074 // Process metadata attached to this instruction.
1075 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1076 I.getAllMetadata(MDs);
1077 for (auto &MD : MDs)
1078 CreateMetadataSlot(MD.second);
1081 /// Clean up after incorporating a function. This is the only way to get out of
1082 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1083 /// incorporation state is indicated by TheFunction != 0.
1084 void SlotTracker::purgeFunction() {
1085 ST_DEBUG("begin purgeFunction!\n");
1086 fMap.clear(); // Simply discard the function level map
1087 TheFunction = nullptr;
1088 FunctionProcessed = false;
1089 ST_DEBUG("end purgeFunction!\n");
1092 /// getGlobalSlot - Get the slot number of a global value.
1093 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1094 // Check for uninitialized state and do lazy initialization.
1095 initializeIfNeeded();
1097 // Find the value in the module map
1098 ValueMap::iterator MI = mMap.find(V);
1099 return MI == mMap.end() ? -1 : (int)MI->second;
1102 /// getMetadataSlot - Get the slot number of a MDNode.
1103 int SlotTracker::getMetadataSlot(const MDNode *N) {
1104 // Check for uninitialized state and do lazy initialization.
1105 initializeIfNeeded();
1107 // Find the MDNode in the module map
1108 mdn_iterator MI = mdnMap.find(N);
1109 return MI == mdnMap.end() ? -1 : (int)MI->second;
1112 /// getLocalSlot - Get the slot number for a value that is local to a function.
1113 int SlotTracker::getLocalSlot(const Value *V) {
1114 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1116 // Check for uninitialized state and do lazy initialization.
1117 initializeIfNeeded();
1119 ValueMap::iterator FI = fMap.find(V);
1120 return FI == fMap.end() ? -1 : (int)FI->second;
1123 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1124 // Check for uninitialized state and do lazy initialization.
1125 initializeIfNeeded();
1127 // Find the AttributeSet in the module map.
1128 as_iterator AI = asMap.find(AS);
1129 return AI == asMap.end() ? -1 : (int)AI->second;
1132 int SlotTracker::getModulePathSlot(StringRef Path) {
1133 // Check for uninitialized state and do lazy initialization.
1134 initializeIndexIfNeeded();
1136 // Find the Module path in the map
1137 auto I = ModulePathMap.find(Path);
1138 return I == ModulePathMap.end() ? -1 : (int)I->second;
1141 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1142 // Check for uninitialized state and do lazy initialization.
1143 initializeIndexIfNeeded();
1145 // Find the GUID in the map
1146 guid_iterator I = GUIDMap.find(GUID);
1147 return I == GUIDMap.end() ? -1 : (int)I->second;
1150 int SlotTracker::getTypeIdSlot(StringRef Id) {
1151 // Check for uninitialized state and do lazy initialization.
1152 initializeIndexIfNeeded();
1154 // Find the TypeId string in the map
1155 auto I = TypeIdMap.find(Id);
1156 return I == TypeIdMap.end() ? -1 : (int)I->second;
1159 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1160 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1161 assert(V && "Can't insert a null Value into SlotTracker!");
1162 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1163 assert(!V->hasName() && "Doesn't need a slot!");
1165 unsigned DestSlot = mNext++;
1166 mMap[V] = DestSlot;
1168 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1169 DestSlot << " [");
1170 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1171 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1172 (isa<Function>(V) ? 'F' :
1173 (isa<GlobalAlias>(V) ? 'A' :
1174 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1177 /// CreateSlot - Create a new slot for the specified value if it has no name.
1178 void SlotTracker::CreateFunctionSlot(const Value *V) {
1179 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1181 unsigned DestSlot = fNext++;
1182 fMap[V] = DestSlot;
1184 // G = Global, F = Function, o = other
1185 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1186 DestSlot << " [o]\n");
1189 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1190 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1191 assert(N && "Can't insert a null Value into SlotTracker!");
1193 // Don't make slots for DIExpressions. We just print them inline everywhere.
1194 if (isa<DIExpression>(N))
1195 return;
1197 unsigned DestSlot = mdnNext;
1198 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1199 return;
1200 ++mdnNext;
1202 // Recursively add any MDNodes referenced by operands.
1203 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1204 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1205 CreateMetadataSlot(Op);
1208 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1209 assert(AS.hasAttributes() && "Doesn't need a slot!");
1211 as_iterator I = asMap.find(AS);
1212 if (I != asMap.end())
1213 return;
1215 unsigned DestSlot = asNext++;
1216 asMap[AS] = DestSlot;
1219 /// Create a new slot for the specified Module
1220 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1221 ModulePathMap[Path] = ModulePathNext++;
1224 /// Create a new slot for the specified GUID
1225 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1226 GUIDMap[GUID] = GUIDNext++;
1229 /// Create a new slot for the specified Id
1230 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1231 TypeIdMap[Id] = TypeIdNext++;
1234 //===----------------------------------------------------------------------===//
1235 // AsmWriter Implementation
1236 //===----------------------------------------------------------------------===//
1238 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1239 TypePrinting *TypePrinter,
1240 SlotTracker *Machine,
1241 const Module *Context);
1243 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1244 TypePrinting *TypePrinter,
1245 SlotTracker *Machine, const Module *Context,
1246 bool FromValue = false);
1248 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1249 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1250 // 'Fast' is an abbreviation for all fast-math-flags.
1251 if (FPO->isFast())
1252 Out << " fast";
1253 else {
1254 if (FPO->hasAllowReassoc())
1255 Out << " reassoc";
1256 if (FPO->hasNoNaNs())
1257 Out << " nnan";
1258 if (FPO->hasNoInfs())
1259 Out << " ninf";
1260 if (FPO->hasNoSignedZeros())
1261 Out << " nsz";
1262 if (FPO->hasAllowReciprocal())
1263 Out << " arcp";
1264 if (FPO->hasAllowContract())
1265 Out << " contract";
1266 if (FPO->hasApproxFunc())
1267 Out << " afn";
1271 if (const OverflowingBinaryOperator *OBO =
1272 dyn_cast<OverflowingBinaryOperator>(U)) {
1273 if (OBO->hasNoUnsignedWrap())
1274 Out << " nuw";
1275 if (OBO->hasNoSignedWrap())
1276 Out << " nsw";
1277 } else if (const PossiblyExactOperator *Div =
1278 dyn_cast<PossiblyExactOperator>(U)) {
1279 if (Div->isExact())
1280 Out << " exact";
1281 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1282 if (GEP->isInBounds())
1283 Out << " inbounds";
1287 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1288 TypePrinting &TypePrinter,
1289 SlotTracker *Machine,
1290 const Module *Context) {
1291 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1292 if (CI->getType()->isIntegerTy(1)) {
1293 Out << (CI->getZExtValue() ? "true" : "false");
1294 return;
1296 Out << CI->getValue();
1297 return;
1300 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1301 const APFloat &APF = CFP->getValueAPF();
1302 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1303 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1304 // We would like to output the FP constant value in exponential notation,
1305 // but we cannot do this if doing so will lose precision. Check here to
1306 // make sure that we only output it in exponential format if we can parse
1307 // the value back and get the same value.
1309 bool ignored;
1310 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1311 bool isInf = APF.isInfinity();
1312 bool isNaN = APF.isNaN();
1313 if (!isInf && !isNaN) {
1314 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1315 SmallString<128> StrVal;
1316 APF.toString(StrVal, 6, 0, false);
1317 // Check to make sure that the stringized number is not some string like
1318 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1319 // that the string matches the "[-+]?[0-9]" regex.
1321 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1322 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1323 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1324 "[-+]?[0-9] regex does not match!");
1325 // Reparse stringized version!
1326 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1327 Out << StrVal;
1328 return;
1331 // Otherwise we could not reparse it to exactly the same value, so we must
1332 // output the string in hexadecimal format! Note that loading and storing
1333 // floating point types changes the bits of NaNs on some hosts, notably
1334 // x86, so we must not use these types.
1335 static_assert(sizeof(double) == sizeof(uint64_t),
1336 "assuming that double is 64 bits!");
1337 APFloat apf = APF;
1338 // Floats are represented in ASCII IR as double, convert.
1339 if (!isDouble)
1340 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1341 &ignored);
1342 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1343 return;
1346 // Either half, or some form of long double.
1347 // These appear as a magic letter identifying the type, then a
1348 // fixed number of hex digits.
1349 Out << "0x";
1350 APInt API = APF.bitcastToAPInt();
1351 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1352 Out << 'K';
1353 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1354 /*Upper=*/true);
1355 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1356 /*Upper=*/true);
1357 return;
1358 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1359 Out << 'L';
1360 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1361 /*Upper=*/true);
1362 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1363 /*Upper=*/true);
1364 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1365 Out << 'M';
1366 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1367 /*Upper=*/true);
1368 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1369 /*Upper=*/true);
1370 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1371 Out << 'H';
1372 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1373 /*Upper=*/true);
1374 } else
1375 llvm_unreachable("Unsupported floating point type");
1376 return;
1379 if (isa<ConstantAggregateZero>(CV)) {
1380 Out << "zeroinitializer";
1381 return;
1384 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1385 Out << "blockaddress(";
1386 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1387 Context);
1388 Out << ", ";
1389 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1390 Context);
1391 Out << ")";
1392 return;
1395 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1396 Type *ETy = CA->getType()->getElementType();
1397 Out << '[';
1398 TypePrinter.print(ETy, Out);
1399 Out << ' ';
1400 WriteAsOperandInternal(Out, CA->getOperand(0),
1401 &TypePrinter, Machine,
1402 Context);
1403 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1404 Out << ", ";
1405 TypePrinter.print(ETy, Out);
1406 Out << ' ';
1407 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1408 Context);
1410 Out << ']';
1411 return;
1414 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1415 // As a special case, print the array as a string if it is an array of
1416 // i8 with ConstantInt values.
1417 if (CA->isString()) {
1418 Out << "c\"";
1419 printEscapedString(CA->getAsString(), Out);
1420 Out << '"';
1421 return;
1424 Type *ETy = CA->getType()->getElementType();
1425 Out << '[';
1426 TypePrinter.print(ETy, Out);
1427 Out << ' ';
1428 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1429 &TypePrinter, Machine,
1430 Context);
1431 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1432 Out << ", ";
1433 TypePrinter.print(ETy, Out);
1434 Out << ' ';
1435 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1436 Machine, Context);
1438 Out << ']';
1439 return;
1442 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1443 if (CS->getType()->isPacked())
1444 Out << '<';
1445 Out << '{';
1446 unsigned N = CS->getNumOperands();
1447 if (N) {
1448 Out << ' ';
1449 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1450 Out << ' ';
1452 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1453 Context);
1455 for (unsigned i = 1; i < N; i++) {
1456 Out << ", ";
1457 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1458 Out << ' ';
1460 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1461 Context);
1463 Out << ' ';
1466 Out << '}';
1467 if (CS->getType()->isPacked())
1468 Out << '>';
1469 return;
1472 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1473 Type *ETy = CV->getType()->getVectorElementType();
1474 Out << '<';
1475 TypePrinter.print(ETy, Out);
1476 Out << ' ';
1477 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1478 Machine, Context);
1479 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1480 Out << ", ";
1481 TypePrinter.print(ETy, Out);
1482 Out << ' ';
1483 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1484 Machine, Context);
1486 Out << '>';
1487 return;
1490 if (isa<ConstantPointerNull>(CV)) {
1491 Out << "null";
1492 return;
1495 if (isa<ConstantTokenNone>(CV)) {
1496 Out << "none";
1497 return;
1500 if (isa<UndefValue>(CV)) {
1501 Out << "undef";
1502 return;
1505 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1506 Out << CE->getOpcodeName();
1507 WriteOptimizationInfo(Out, CE);
1508 if (CE->isCompare())
1509 Out << ' ' << CmpInst::getPredicateName(
1510 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1511 Out << " (";
1513 Optional<unsigned> InRangeOp;
1514 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1515 TypePrinter.print(GEP->getSourceElementType(), Out);
1516 Out << ", ";
1517 InRangeOp = GEP->getInRangeIndex();
1518 if (InRangeOp)
1519 ++*InRangeOp;
1522 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1523 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1524 Out << "inrange ";
1525 TypePrinter.print((*OI)->getType(), Out);
1526 Out << ' ';
1527 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1528 if (OI+1 != CE->op_end())
1529 Out << ", ";
1532 if (CE->hasIndices()) {
1533 ArrayRef<unsigned> Indices = CE->getIndices();
1534 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1535 Out << ", " << Indices[i];
1538 if (CE->isCast()) {
1539 Out << " to ";
1540 TypePrinter.print(CE->getType(), Out);
1543 Out << ')';
1544 return;
1547 Out << "<placeholder or erroneous Constant>";
1550 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1551 TypePrinting *TypePrinter, SlotTracker *Machine,
1552 const Module *Context) {
1553 Out << "!{";
1554 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1555 const Metadata *MD = Node->getOperand(mi);
1556 if (!MD)
1557 Out << "null";
1558 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1559 Value *V = MDV->getValue();
1560 TypePrinter->print(V->getType(), Out);
1561 Out << ' ';
1562 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1563 } else {
1564 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1566 if (mi + 1 != me)
1567 Out << ", ";
1570 Out << "}";
1573 namespace {
1575 struct FieldSeparator {
1576 bool Skip = true;
1577 const char *Sep;
1579 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1582 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1583 if (FS.Skip) {
1584 FS.Skip = false;
1585 return OS;
1587 return OS << FS.Sep;
1590 struct MDFieldPrinter {
1591 raw_ostream &Out;
1592 FieldSeparator FS;
1593 TypePrinting *TypePrinter = nullptr;
1594 SlotTracker *Machine = nullptr;
1595 const Module *Context = nullptr;
1597 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1598 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1599 SlotTracker *Machine, const Module *Context)
1600 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1603 void printTag(const DINode *N);
1604 void printMacinfoType(const DIMacroNode *N);
1605 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1606 void printString(StringRef Name, StringRef Value,
1607 bool ShouldSkipEmpty = true);
1608 void printMetadata(StringRef Name, const Metadata *MD,
1609 bool ShouldSkipNull = true);
1610 template <class IntTy>
1611 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1612 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1613 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1614 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1615 template <class IntTy, class Stringifier>
1616 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1617 bool ShouldSkipZero = true);
1618 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1619 void printNameTableKind(StringRef Name,
1620 DICompileUnit::DebugNameTableKind NTK);
1623 } // end anonymous namespace
1625 void MDFieldPrinter::printTag(const DINode *N) {
1626 Out << FS << "tag: ";
1627 auto Tag = dwarf::TagString(N->getTag());
1628 if (!Tag.empty())
1629 Out << Tag;
1630 else
1631 Out << N->getTag();
1634 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1635 Out << FS << "type: ";
1636 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1637 if (!Type.empty())
1638 Out << Type;
1639 else
1640 Out << N->getMacinfoType();
1643 void MDFieldPrinter::printChecksum(
1644 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1645 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1646 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1649 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1650 bool ShouldSkipEmpty) {
1651 if (ShouldSkipEmpty && Value.empty())
1652 return;
1654 Out << FS << Name << ": \"";
1655 printEscapedString(Value, Out);
1656 Out << "\"";
1659 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1660 TypePrinting *TypePrinter,
1661 SlotTracker *Machine,
1662 const Module *Context) {
1663 if (!MD) {
1664 Out << "null";
1665 return;
1667 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1670 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1671 bool ShouldSkipNull) {
1672 if (ShouldSkipNull && !MD)
1673 return;
1675 Out << FS << Name << ": ";
1676 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1679 template <class IntTy>
1680 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1681 if (ShouldSkipZero && !Int)
1682 return;
1684 Out << FS << Name << ": " << Int;
1687 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1688 Optional<bool> Default) {
1689 if (Default && Value == *Default)
1690 return;
1691 Out << FS << Name << ": " << (Value ? "true" : "false");
1694 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1695 if (!Flags)
1696 return;
1698 Out << FS << Name << ": ";
1700 SmallVector<DINode::DIFlags, 8> SplitFlags;
1701 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1703 FieldSeparator FlagsFS(" | ");
1704 for (auto F : SplitFlags) {
1705 auto StringF = DINode::getFlagString(F);
1706 assert(!StringF.empty() && "Expected valid flag");
1707 Out << FlagsFS << StringF;
1709 if (Extra || SplitFlags.empty())
1710 Out << FlagsFS << Extra;
1713 void MDFieldPrinter::printDISPFlags(StringRef Name,
1714 DISubprogram::DISPFlags Flags) {
1715 // Always print this field, because no flags in the IR at all will be
1716 // interpreted as old-style isDefinition: true.
1717 Out << FS << Name << ": ";
1719 if (!Flags) {
1720 Out << 0;
1721 return;
1724 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1725 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1727 FieldSeparator FlagsFS(" | ");
1728 for (auto F : SplitFlags) {
1729 auto StringF = DISubprogram::getFlagString(F);
1730 assert(!StringF.empty() && "Expected valid flag");
1731 Out << FlagsFS << StringF;
1733 if (Extra || SplitFlags.empty())
1734 Out << FlagsFS << Extra;
1737 void MDFieldPrinter::printEmissionKind(StringRef Name,
1738 DICompileUnit::DebugEmissionKind EK) {
1739 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1742 void MDFieldPrinter::printNameTableKind(StringRef Name,
1743 DICompileUnit::DebugNameTableKind NTK) {
1744 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1745 return;
1746 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1749 template <class IntTy, class Stringifier>
1750 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1751 Stringifier toString, bool ShouldSkipZero) {
1752 if (!Value)
1753 return;
1755 Out << FS << Name << ": ";
1756 auto S = toString(Value);
1757 if (!S.empty())
1758 Out << S;
1759 else
1760 Out << Value;
1763 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1764 TypePrinting *TypePrinter, SlotTracker *Machine,
1765 const Module *Context) {
1766 Out << "!GenericDINode(";
1767 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1768 Printer.printTag(N);
1769 Printer.printString("header", N->getHeader());
1770 if (N->getNumDwarfOperands()) {
1771 Out << Printer.FS << "operands: {";
1772 FieldSeparator IFS;
1773 for (auto &I : N->dwarf_operands()) {
1774 Out << IFS;
1775 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1777 Out << "}";
1779 Out << ")";
1782 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1783 TypePrinting *TypePrinter, SlotTracker *Machine,
1784 const Module *Context) {
1785 Out << "!DILocation(";
1786 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1787 // Always output the line, since 0 is a relevant and important value for it.
1788 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1789 Printer.printInt("column", DL->getColumn());
1790 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1791 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1792 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1793 /* Default */ false);
1794 Out << ")";
1797 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1798 TypePrinting *TypePrinter, SlotTracker *Machine,
1799 const Module *Context) {
1800 Out << "!DISubrange(";
1801 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1802 if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1803 Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1804 else
1805 Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
1806 /*ShouldSkipNull */ false);
1807 Printer.printInt("lowerBound", N->getLowerBound());
1808 Out << ")";
1811 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1812 TypePrinting *, SlotTracker *, const Module *) {
1813 Out << "!DIEnumerator(";
1814 MDFieldPrinter Printer(Out);
1815 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1816 if (N->isUnsigned()) {
1817 auto Value = static_cast<uint64_t>(N->getValue());
1818 Printer.printInt("value", Value, /* ShouldSkipZero */ false);
1819 Printer.printBool("isUnsigned", true);
1820 } else {
1821 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1823 Out << ")";
1826 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1827 TypePrinting *, SlotTracker *, const Module *) {
1828 Out << "!DIBasicType(";
1829 MDFieldPrinter Printer(Out);
1830 if (N->getTag() != dwarf::DW_TAG_base_type)
1831 Printer.printTag(N);
1832 Printer.printString("name", N->getName());
1833 Printer.printInt("size", N->getSizeInBits());
1834 Printer.printInt("align", N->getAlignInBits());
1835 Printer.printDwarfEnum("encoding", N->getEncoding(),
1836 dwarf::AttributeEncodingString);
1837 Printer.printDIFlags("flags", N->getFlags());
1838 Out << ")";
1841 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1842 TypePrinting *TypePrinter, SlotTracker *Machine,
1843 const Module *Context) {
1844 Out << "!DIDerivedType(";
1845 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1846 Printer.printTag(N);
1847 Printer.printString("name", N->getName());
1848 Printer.printMetadata("scope", N->getRawScope());
1849 Printer.printMetadata("file", N->getRawFile());
1850 Printer.printInt("line", N->getLine());
1851 Printer.printMetadata("baseType", N->getRawBaseType(),
1852 /* ShouldSkipNull */ false);
1853 Printer.printInt("size", N->getSizeInBits());
1854 Printer.printInt("align", N->getAlignInBits());
1855 Printer.printInt("offset", N->getOffsetInBits());
1856 Printer.printDIFlags("flags", N->getFlags());
1857 Printer.printMetadata("extraData", N->getRawExtraData());
1858 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1859 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1860 /* ShouldSkipZero */ false);
1861 Out << ")";
1864 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1865 TypePrinting *TypePrinter,
1866 SlotTracker *Machine, const Module *Context) {
1867 Out << "!DICompositeType(";
1868 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1869 Printer.printTag(N);
1870 Printer.printString("name", N->getName());
1871 Printer.printMetadata("scope", N->getRawScope());
1872 Printer.printMetadata("file", N->getRawFile());
1873 Printer.printInt("line", N->getLine());
1874 Printer.printMetadata("baseType", N->getRawBaseType());
1875 Printer.printInt("size", N->getSizeInBits());
1876 Printer.printInt("align", N->getAlignInBits());
1877 Printer.printInt("offset", N->getOffsetInBits());
1878 Printer.printDIFlags("flags", N->getFlags());
1879 Printer.printMetadata("elements", N->getRawElements());
1880 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1881 dwarf::LanguageString);
1882 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1883 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1884 Printer.printString("identifier", N->getIdentifier());
1885 Printer.printMetadata("discriminator", N->getRawDiscriminator());
1886 Out << ")";
1889 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1890 TypePrinting *TypePrinter,
1891 SlotTracker *Machine, const Module *Context) {
1892 Out << "!DISubroutineType(";
1893 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1894 Printer.printDIFlags("flags", N->getFlags());
1895 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1896 Printer.printMetadata("types", N->getRawTypeArray(),
1897 /* ShouldSkipNull */ false);
1898 Out << ")";
1901 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1902 SlotTracker *, const Module *) {
1903 Out << "!DIFile(";
1904 MDFieldPrinter Printer(Out);
1905 Printer.printString("filename", N->getFilename(),
1906 /* ShouldSkipEmpty */ false);
1907 Printer.printString("directory", N->getDirectory(),
1908 /* ShouldSkipEmpty */ false);
1909 // Print all values for checksum together, or not at all.
1910 if (N->getChecksum())
1911 Printer.printChecksum(*N->getChecksum());
1912 Printer.printString("source", N->getSource().getValueOr(StringRef()),
1913 /* ShouldSkipEmpty */ true);
1914 Out << ")";
1917 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1918 TypePrinting *TypePrinter, SlotTracker *Machine,
1919 const Module *Context) {
1920 Out << "!DICompileUnit(";
1921 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1922 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1923 dwarf::LanguageString, /* ShouldSkipZero */ false);
1924 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1925 Printer.printString("producer", N->getProducer());
1926 Printer.printBool("isOptimized", N->isOptimized());
1927 Printer.printString("flags", N->getFlags());
1928 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1929 /* ShouldSkipZero */ false);
1930 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1931 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1932 Printer.printMetadata("enums", N->getRawEnumTypes());
1933 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1934 Printer.printMetadata("globals", N->getRawGlobalVariables());
1935 Printer.printMetadata("imports", N->getRawImportedEntities());
1936 Printer.printMetadata("macros", N->getRawMacros());
1937 Printer.printInt("dwoId", N->getDWOId());
1938 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1939 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1940 false);
1941 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
1942 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
1943 Out << ")";
1946 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1947 TypePrinting *TypePrinter, SlotTracker *Machine,
1948 const Module *Context) {
1949 Out << "!DISubprogram(";
1950 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1951 Printer.printString("name", N->getName());
1952 Printer.printString("linkageName", N->getLinkageName());
1953 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1954 Printer.printMetadata("file", N->getRawFile());
1955 Printer.printInt("line", N->getLine());
1956 Printer.printMetadata("type", N->getRawType());
1957 Printer.printInt("scopeLine", N->getScopeLine());
1958 Printer.printMetadata("containingType", N->getRawContainingType());
1959 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1960 N->getVirtualIndex() != 0)
1961 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1962 Printer.printInt("thisAdjustment", N->getThisAdjustment());
1963 Printer.printDIFlags("flags", N->getFlags());
1964 Printer.printDISPFlags("spFlags", N->getSPFlags());
1965 Printer.printMetadata("unit", N->getRawUnit());
1966 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1967 Printer.printMetadata("declaration", N->getRawDeclaration());
1968 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
1969 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1970 Out << ")";
1973 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1974 TypePrinting *TypePrinter, SlotTracker *Machine,
1975 const Module *Context) {
1976 Out << "!DILexicalBlock(";
1977 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1978 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1979 Printer.printMetadata("file", N->getRawFile());
1980 Printer.printInt("line", N->getLine());
1981 Printer.printInt("column", N->getColumn());
1982 Out << ")";
1985 static void writeDILexicalBlockFile(raw_ostream &Out,
1986 const DILexicalBlockFile *N,
1987 TypePrinting *TypePrinter,
1988 SlotTracker *Machine,
1989 const Module *Context) {
1990 Out << "!DILexicalBlockFile(";
1991 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1992 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1993 Printer.printMetadata("file", N->getRawFile());
1994 Printer.printInt("discriminator", N->getDiscriminator(),
1995 /* ShouldSkipZero */ false);
1996 Out << ")";
1999 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2000 TypePrinting *TypePrinter, SlotTracker *Machine,
2001 const Module *Context) {
2002 Out << "!DINamespace(";
2003 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2004 Printer.printString("name", N->getName());
2005 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2006 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2007 Out << ")";
2010 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2011 TypePrinting *TypePrinter, SlotTracker *Machine,
2012 const Module *Context) {
2013 Out << "!DICommonBlock(";
2014 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2015 Printer.printMetadata("scope", N->getRawScope(), false);
2016 Printer.printMetadata("declaration", N->getRawDecl(), false);
2017 Printer.printString("name", N->getName());
2018 Printer.printMetadata("file", N->getRawFile());
2019 Printer.printInt("line", N->getLineNo());
2020 Out << ")";
2023 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2024 TypePrinting *TypePrinter, SlotTracker *Machine,
2025 const Module *Context) {
2026 Out << "!DIMacro(";
2027 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2028 Printer.printMacinfoType(N);
2029 Printer.printInt("line", N->getLine());
2030 Printer.printString("name", N->getName());
2031 Printer.printString("value", N->getValue());
2032 Out << ")";
2035 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2036 TypePrinting *TypePrinter, SlotTracker *Machine,
2037 const Module *Context) {
2038 Out << "!DIMacroFile(";
2039 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2040 Printer.printInt("line", N->getLine());
2041 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2042 Printer.printMetadata("nodes", N->getRawElements());
2043 Out << ")";
2046 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2047 TypePrinting *TypePrinter, SlotTracker *Machine,
2048 const Module *Context) {
2049 Out << "!DIModule(";
2050 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2051 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2052 Printer.printString("name", N->getName());
2053 Printer.printString("configMacros", N->getConfigurationMacros());
2054 Printer.printString("includePath", N->getIncludePath());
2055 Printer.printString("isysroot", N->getISysRoot());
2056 Out << ")";
2060 static void writeDITemplateTypeParameter(raw_ostream &Out,
2061 const DITemplateTypeParameter *N,
2062 TypePrinting *TypePrinter,
2063 SlotTracker *Machine,
2064 const Module *Context) {
2065 Out << "!DITemplateTypeParameter(";
2066 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2067 Printer.printString("name", N->getName());
2068 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2069 Out << ")";
2072 static void writeDITemplateValueParameter(raw_ostream &Out,
2073 const DITemplateValueParameter *N,
2074 TypePrinting *TypePrinter,
2075 SlotTracker *Machine,
2076 const Module *Context) {
2077 Out << "!DITemplateValueParameter(";
2078 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2079 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2080 Printer.printTag(N);
2081 Printer.printString("name", N->getName());
2082 Printer.printMetadata("type", N->getRawType());
2083 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2084 Out << ")";
2087 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2088 TypePrinting *TypePrinter,
2089 SlotTracker *Machine, const Module *Context) {
2090 Out << "!DIGlobalVariable(";
2091 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2092 Printer.printString("name", N->getName());
2093 Printer.printString("linkageName", N->getLinkageName());
2094 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2095 Printer.printMetadata("file", N->getRawFile());
2096 Printer.printInt("line", N->getLine());
2097 Printer.printMetadata("type", N->getRawType());
2098 Printer.printBool("isLocal", N->isLocalToUnit());
2099 Printer.printBool("isDefinition", N->isDefinition());
2100 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2101 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2102 Printer.printInt("align", N->getAlignInBits());
2103 Out << ")";
2106 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2107 TypePrinting *TypePrinter,
2108 SlotTracker *Machine, const Module *Context) {
2109 Out << "!DILocalVariable(";
2110 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2111 Printer.printString("name", N->getName());
2112 Printer.printInt("arg", N->getArg());
2113 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2114 Printer.printMetadata("file", N->getRawFile());
2115 Printer.printInt("line", N->getLine());
2116 Printer.printMetadata("type", N->getRawType());
2117 Printer.printDIFlags("flags", N->getFlags());
2118 Printer.printInt("align", N->getAlignInBits());
2119 Out << ")";
2122 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2123 TypePrinting *TypePrinter,
2124 SlotTracker *Machine, const Module *Context) {
2125 Out << "!DILabel(";
2126 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2127 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2128 Printer.printString("name", N->getName());
2129 Printer.printMetadata("file", N->getRawFile());
2130 Printer.printInt("line", N->getLine());
2131 Out << ")";
2134 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2135 TypePrinting *TypePrinter, SlotTracker *Machine,
2136 const Module *Context) {
2137 Out << "!DIExpression(";
2138 FieldSeparator FS;
2139 if (N->isValid()) {
2140 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
2141 auto OpStr = dwarf::OperationEncodingString(I->getOp());
2142 assert(!OpStr.empty() && "Expected valid opcode");
2144 Out << FS << OpStr;
2145 if (I->getOp() == dwarf::DW_OP_LLVM_convert) {
2146 Out << FS << I->getArg(0);
2147 Out << FS << dwarf::AttributeEncodingString(I->getArg(1));
2148 } else {
2149 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2150 Out << FS << I->getArg(A);
2153 } else {
2154 for (const auto &I : N->getElements())
2155 Out << FS << I;
2157 Out << ")";
2160 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2161 const DIGlobalVariableExpression *N,
2162 TypePrinting *TypePrinter,
2163 SlotTracker *Machine,
2164 const Module *Context) {
2165 Out << "!DIGlobalVariableExpression(";
2166 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2167 Printer.printMetadata("var", N->getVariable());
2168 Printer.printMetadata("expr", N->getExpression());
2169 Out << ")";
2172 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2173 TypePrinting *TypePrinter, SlotTracker *Machine,
2174 const Module *Context) {
2175 Out << "!DIObjCProperty(";
2176 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2177 Printer.printString("name", N->getName());
2178 Printer.printMetadata("file", N->getRawFile());
2179 Printer.printInt("line", N->getLine());
2180 Printer.printString("setter", N->getSetterName());
2181 Printer.printString("getter", N->getGetterName());
2182 Printer.printInt("attributes", N->getAttributes());
2183 Printer.printMetadata("type", N->getRawType());
2184 Out << ")";
2187 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2188 TypePrinting *TypePrinter,
2189 SlotTracker *Machine, const Module *Context) {
2190 Out << "!DIImportedEntity(";
2191 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2192 Printer.printTag(N);
2193 Printer.printString("name", N->getName());
2194 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2195 Printer.printMetadata("entity", N->getRawEntity());
2196 Printer.printMetadata("file", N->getRawFile());
2197 Printer.printInt("line", N->getLine());
2198 Out << ")";
2201 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2202 TypePrinting *TypePrinter,
2203 SlotTracker *Machine,
2204 const Module *Context) {
2205 if (Node->isDistinct())
2206 Out << "distinct ";
2207 else if (Node->isTemporary())
2208 Out << "<temporary!> "; // Handle broken code.
2210 switch (Node->getMetadataID()) {
2211 default:
2212 llvm_unreachable("Expected uniquable MDNode");
2213 #define HANDLE_MDNODE_LEAF(CLASS) \
2214 case Metadata::CLASS##Kind: \
2215 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
2216 break;
2217 #include "llvm/IR/Metadata.def"
2221 // Full implementation of printing a Value as an operand with support for
2222 // TypePrinting, etc.
2223 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2224 TypePrinting *TypePrinter,
2225 SlotTracker *Machine,
2226 const Module *Context) {
2227 if (V->hasName()) {
2228 PrintLLVMName(Out, V);
2229 return;
2232 const Constant *CV = dyn_cast<Constant>(V);
2233 if (CV && !isa<GlobalValue>(CV)) {
2234 assert(TypePrinter && "Constants require TypePrinting!");
2235 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2236 return;
2239 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2240 Out << "asm ";
2241 if (IA->hasSideEffects())
2242 Out << "sideeffect ";
2243 if (IA->isAlignStack())
2244 Out << "alignstack ";
2245 // We don't emit the AD_ATT dialect as it's the assumed default.
2246 if (IA->getDialect() == InlineAsm::AD_Intel)
2247 Out << "inteldialect ";
2248 Out << '"';
2249 printEscapedString(IA->getAsmString(), Out);
2250 Out << "\", \"";
2251 printEscapedString(IA->getConstraintString(), Out);
2252 Out << '"';
2253 return;
2256 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2257 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2258 Context, /* FromValue */ true);
2259 return;
2262 char Prefix = '%';
2263 int Slot;
2264 // If we have a SlotTracker, use it.
2265 if (Machine) {
2266 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2267 Slot = Machine->getGlobalSlot(GV);
2268 Prefix = '@';
2269 } else {
2270 Slot = Machine->getLocalSlot(V);
2272 // If the local value didn't succeed, then we may be referring to a value
2273 // from a different function. Translate it, as this can happen when using
2274 // address of blocks.
2275 if (Slot == -1)
2276 if ((Machine = createSlotTracker(V))) {
2277 Slot = Machine->getLocalSlot(V);
2278 delete Machine;
2281 } else if ((Machine = createSlotTracker(V))) {
2282 // Otherwise, create one to get the # and then destroy it.
2283 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2284 Slot = Machine->getGlobalSlot(GV);
2285 Prefix = '@';
2286 } else {
2287 Slot = Machine->getLocalSlot(V);
2289 delete Machine;
2290 Machine = nullptr;
2291 } else {
2292 Slot = -1;
2295 if (Slot != -1)
2296 Out << Prefix << Slot;
2297 else
2298 Out << "<badref>";
2301 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2302 TypePrinting *TypePrinter,
2303 SlotTracker *Machine, const Module *Context,
2304 bool FromValue) {
2305 // Write DIExpressions inline when used as a value. Improves readability of
2306 // debug info intrinsics.
2307 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2308 writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2309 return;
2312 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2313 std::unique_ptr<SlotTracker> MachineStorage;
2314 if (!Machine) {
2315 MachineStorage = make_unique<SlotTracker>(Context);
2316 Machine = MachineStorage.get();
2318 int Slot = Machine->getMetadataSlot(N);
2319 if (Slot == -1) {
2320 if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2321 writeDILocation(Out, Loc, TypePrinter, Machine, Context);
2322 return;
2324 // Give the pointer value instead of "badref", since this comes up all
2325 // the time when debugging.
2326 Out << "<" << N << ">";
2327 } else
2328 Out << '!' << Slot;
2329 return;
2332 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2333 Out << "!\"";
2334 printEscapedString(MDS->getString(), Out);
2335 Out << '"';
2336 return;
2339 auto *V = cast<ValueAsMetadata>(MD);
2340 assert(TypePrinter && "TypePrinter required for metadata values");
2341 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2342 "Unexpected function-local metadata outside of value argument");
2344 TypePrinter->print(V->getValue()->getType(), Out);
2345 Out << ' ';
2346 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2349 namespace {
2351 class AssemblyWriter {
2352 formatted_raw_ostream &Out;
2353 const Module *TheModule = nullptr;
2354 const ModuleSummaryIndex *TheIndex = nullptr;
2355 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2356 SlotTracker &Machine;
2357 TypePrinting TypePrinter;
2358 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2359 SetVector<const Comdat *> Comdats;
2360 bool IsForDebug;
2361 bool ShouldPreserveUseListOrder;
2362 UseListOrderStack UseListOrders;
2363 SmallVector<StringRef, 8> MDNames;
2364 /// Synchronization scope names registered with LLVMContext.
2365 SmallVector<StringRef, 8> SSNs;
2366 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2368 public:
2369 /// Construct an AssemblyWriter with an external SlotTracker
2370 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2371 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2372 bool ShouldPreserveUseListOrder = false);
2374 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2375 const ModuleSummaryIndex *Index, bool IsForDebug);
2377 void printMDNodeBody(const MDNode *MD);
2378 void printNamedMDNode(const NamedMDNode *NMD);
2380 void printModule(const Module *M);
2382 void writeOperand(const Value *Op, bool PrintType);
2383 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2384 void writeOperandBundles(const CallBase *Call);
2385 void writeSyncScope(const LLVMContext &Context,
2386 SyncScope::ID SSID);
2387 void writeAtomic(const LLVMContext &Context,
2388 AtomicOrdering Ordering,
2389 SyncScope::ID SSID);
2390 void writeAtomicCmpXchg(const LLVMContext &Context,
2391 AtomicOrdering SuccessOrdering,
2392 AtomicOrdering FailureOrdering,
2393 SyncScope::ID SSID);
2395 void writeAllMDNodes();
2396 void writeMDNode(unsigned Slot, const MDNode *Node);
2397 void writeAllAttributeGroups();
2399 void printTypeIdentities();
2400 void printGlobal(const GlobalVariable *GV);
2401 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2402 void printComdat(const Comdat *C);
2403 void printFunction(const Function *F);
2404 void printArgument(const Argument *FA, AttributeSet Attrs);
2405 void printBasicBlock(const BasicBlock *BB);
2406 void printInstructionLine(const Instruction &I);
2407 void printInstruction(const Instruction &I);
2409 void printUseListOrder(const UseListOrder &Order);
2410 void printUseLists(const Function *F);
2412 void printModuleSummaryIndex();
2413 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2414 void printSummary(const GlobalValueSummary &Summary);
2415 void printAliasSummary(const AliasSummary *AS);
2416 void printGlobalVarSummary(const GlobalVarSummary *GS);
2417 void printFunctionSummary(const FunctionSummary *FS);
2418 void printTypeIdSummary(const TypeIdSummary &TIS);
2419 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2420 void printTypeTestResolution(const TypeTestResolution &TTRes);
2421 void printArgs(const std::vector<uint64_t> &Args);
2422 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2423 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2424 void printVFuncId(const FunctionSummary::VFuncId VFId);
2425 void
2426 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2427 const char *Tag);
2428 void
2429 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2430 const char *Tag);
2432 private:
2433 /// Print out metadata attachments.
2434 void printMetadataAttachments(
2435 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2436 StringRef Separator);
2438 // printInfoComment - Print a little comment after the instruction indicating
2439 // which slot it occupies.
2440 void printInfoComment(const Value &V);
2442 // printGCRelocateComment - print comment after call to the gc.relocate
2443 // intrinsic indicating base and derived pointer names.
2444 void printGCRelocateComment(const GCRelocateInst &Relocate);
2447 } // end anonymous namespace
2449 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2450 const Module *M, AssemblyAnnotationWriter *AAW,
2451 bool IsForDebug, bool ShouldPreserveUseListOrder)
2452 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2453 IsForDebug(IsForDebug),
2454 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2455 if (!TheModule)
2456 return;
2457 for (const GlobalObject &GO : TheModule->global_objects())
2458 if (const Comdat *C = GO.getComdat())
2459 Comdats.insert(C);
2462 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2463 const ModuleSummaryIndex *Index, bool IsForDebug)
2464 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2465 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2467 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2468 if (!Operand) {
2469 Out << "<null operand!>";
2470 return;
2472 if (PrintType) {
2473 TypePrinter.print(Operand->getType(), Out);
2474 Out << ' ';
2476 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2479 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2480 SyncScope::ID SSID) {
2481 switch (SSID) {
2482 case SyncScope::System: {
2483 break;
2485 default: {
2486 if (SSNs.empty())
2487 Context.getSyncScopeNames(SSNs);
2489 Out << " syncscope(\"";
2490 printEscapedString(SSNs[SSID], Out);
2491 Out << "\")";
2492 break;
2497 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2498 AtomicOrdering Ordering,
2499 SyncScope::ID SSID) {
2500 if (Ordering == AtomicOrdering::NotAtomic)
2501 return;
2503 writeSyncScope(Context, SSID);
2504 Out << " " << toIRString(Ordering);
2507 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2508 AtomicOrdering SuccessOrdering,
2509 AtomicOrdering FailureOrdering,
2510 SyncScope::ID SSID) {
2511 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2512 FailureOrdering != AtomicOrdering::NotAtomic);
2514 writeSyncScope(Context, SSID);
2515 Out << " " << toIRString(SuccessOrdering);
2516 Out << " " << toIRString(FailureOrdering);
2519 void AssemblyWriter::writeParamOperand(const Value *Operand,
2520 AttributeSet Attrs) {
2521 if (!Operand) {
2522 Out << "<null operand!>";
2523 return;
2526 // Print the type
2527 TypePrinter.print(Operand->getType(), Out);
2528 // Print parameter attributes list
2529 if (Attrs.hasAttributes())
2530 Out << ' ' << Attrs.getAsString();
2531 Out << ' ';
2532 // Print the operand
2533 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2536 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2537 if (!Call->hasOperandBundles())
2538 return;
2540 Out << " [ ";
2542 bool FirstBundle = true;
2543 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2544 OperandBundleUse BU = Call->getOperandBundleAt(i);
2546 if (!FirstBundle)
2547 Out << ", ";
2548 FirstBundle = false;
2550 Out << '"';
2551 printEscapedString(BU.getTagName(), Out);
2552 Out << '"';
2554 Out << '(';
2556 bool FirstInput = true;
2557 for (const auto &Input : BU.Inputs) {
2558 if (!FirstInput)
2559 Out << ", ";
2560 FirstInput = false;
2562 TypePrinter.print(Input->getType(), Out);
2563 Out << " ";
2564 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2567 Out << ')';
2570 Out << " ]";
2573 void AssemblyWriter::printModule(const Module *M) {
2574 Machine.initializeIfNeeded();
2576 if (ShouldPreserveUseListOrder)
2577 UseListOrders = predictUseListOrder(M);
2579 if (!M->getModuleIdentifier().empty() &&
2580 // Don't print the ID if it will start a new line (which would
2581 // require a comment char before it).
2582 M->getModuleIdentifier().find('\n') == std::string::npos)
2583 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2585 if (!M->getSourceFileName().empty()) {
2586 Out << "source_filename = \"";
2587 printEscapedString(M->getSourceFileName(), Out);
2588 Out << "\"\n";
2591 const std::string &DL = M->getDataLayoutStr();
2592 if (!DL.empty())
2593 Out << "target datalayout = \"" << DL << "\"\n";
2594 if (!M->getTargetTriple().empty())
2595 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2597 if (!M->getModuleInlineAsm().empty()) {
2598 Out << '\n';
2600 // Split the string into lines, to make it easier to read the .ll file.
2601 StringRef Asm = M->getModuleInlineAsm();
2602 do {
2603 StringRef Front;
2604 std::tie(Front, Asm) = Asm.split('\n');
2606 // We found a newline, print the portion of the asm string from the
2607 // last newline up to this newline.
2608 Out << "module asm \"";
2609 printEscapedString(Front, Out);
2610 Out << "\"\n";
2611 } while (!Asm.empty());
2614 printTypeIdentities();
2616 // Output all comdats.
2617 if (!Comdats.empty())
2618 Out << '\n';
2619 for (const Comdat *C : Comdats) {
2620 printComdat(C);
2621 if (C != Comdats.back())
2622 Out << '\n';
2625 // Output all globals.
2626 if (!M->global_empty()) Out << '\n';
2627 for (const GlobalVariable &GV : M->globals()) {
2628 printGlobal(&GV); Out << '\n';
2631 // Output all aliases.
2632 if (!M->alias_empty()) Out << "\n";
2633 for (const GlobalAlias &GA : M->aliases())
2634 printIndirectSymbol(&GA);
2636 // Output all ifuncs.
2637 if (!M->ifunc_empty()) Out << "\n";
2638 for (const GlobalIFunc &GI : M->ifuncs())
2639 printIndirectSymbol(&GI);
2641 // Output global use-lists.
2642 printUseLists(nullptr);
2644 // Output all of the functions.
2645 for (const Function &F : *M)
2646 printFunction(&F);
2647 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2649 // Output all attribute groups.
2650 if (!Machine.as_empty()) {
2651 Out << '\n';
2652 writeAllAttributeGroups();
2655 // Output named metadata.
2656 if (!M->named_metadata_empty()) Out << '\n';
2658 for (const NamedMDNode &Node : M->named_metadata())
2659 printNamedMDNode(&Node);
2661 // Output metadata.
2662 if (!Machine.mdn_empty()) {
2663 Out << '\n';
2664 writeAllMDNodes();
2668 void AssemblyWriter::printModuleSummaryIndex() {
2669 assert(TheIndex);
2670 Machine.initializeIndexIfNeeded();
2672 Out << "\n";
2674 // Print module path entries. To print in order, add paths to a vector
2675 // indexed by module slot.
2676 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2677 std::string RegularLTOModuleName = "[Regular LTO]";
2678 moduleVec.resize(TheIndex->modulePaths().size());
2679 for (auto &ModPath : TheIndex->modulePaths())
2680 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2681 // A module id of -1 is a special entry for a regular LTO module created
2682 // during the thin link.
2683 ModPath.second.first == -1u ? RegularLTOModuleName
2684 : (std::string)ModPath.first(),
2685 ModPath.second.second);
2687 unsigned i = 0;
2688 for (auto &ModPair : moduleVec) {
2689 Out << "^" << i++ << " = module: (";
2690 Out << "path: \"";
2691 printEscapedString(ModPair.first, Out);
2692 Out << "\", hash: (";
2693 FieldSeparator FS;
2694 for (auto Hash : ModPair.second)
2695 Out << FS << Hash;
2696 Out << "))\n";
2699 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2700 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2701 for (auto &GlobalList : *TheIndex) {
2702 auto GUID = GlobalList.first;
2703 for (auto &Summary : GlobalList.second.SummaryList)
2704 SummaryToGUIDMap[Summary.get()] = GUID;
2707 // Print the global value summary entries.
2708 for (auto &GlobalList : *TheIndex) {
2709 auto GUID = GlobalList.first;
2710 auto VI = TheIndex->getValueInfo(GlobalList);
2711 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2714 // Print the TypeIdMap entries.
2715 for (auto TidIter = TheIndex->typeIds().begin();
2716 TidIter != TheIndex->typeIds().end(); TidIter++) {
2717 Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2718 << " = typeid: (name: \"" << TidIter->second.first << "\"";
2719 printTypeIdSummary(TidIter->second.second);
2720 Out << ") ; guid = " << TidIter->first << "\n";
2723 // Print the TypeIdCompatibleVtableMap entries.
2724 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2725 auto GUID = GlobalValue::getGUID(TId.first);
2726 Out << "^" << Machine.getGUIDSlot(GUID)
2727 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2728 printTypeIdCompatibleVtableSummary(TId.second);
2729 Out << ") ; guid = " << GUID << "\n";
2733 static const char *
2734 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2735 switch (K) {
2736 case WholeProgramDevirtResolution::Indir:
2737 return "indir";
2738 case WholeProgramDevirtResolution::SingleImpl:
2739 return "singleImpl";
2740 case WholeProgramDevirtResolution::BranchFunnel:
2741 return "branchFunnel";
2743 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2746 static const char *getWholeProgDevirtResByArgKindName(
2747 WholeProgramDevirtResolution::ByArg::Kind K) {
2748 switch (K) {
2749 case WholeProgramDevirtResolution::ByArg::Indir:
2750 return "indir";
2751 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2752 return "uniformRetVal";
2753 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2754 return "uniqueRetVal";
2755 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2756 return "virtualConstProp";
2758 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2761 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2762 switch (K) {
2763 case TypeTestResolution::Unsat:
2764 return "unsat";
2765 case TypeTestResolution::ByteArray:
2766 return "byteArray";
2767 case TypeTestResolution::Inline:
2768 return "inline";
2769 case TypeTestResolution::Single:
2770 return "single";
2771 case TypeTestResolution::AllOnes:
2772 return "allOnes";
2774 llvm_unreachable("invalid TypeTestResolution kind");
2777 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2778 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2779 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2781 // The following fields are only used if the target does not support the use
2782 // of absolute symbols to store constants. Print only if non-zero.
2783 if (TTRes.AlignLog2)
2784 Out << ", alignLog2: " << TTRes.AlignLog2;
2785 if (TTRes.SizeM1)
2786 Out << ", sizeM1: " << TTRes.SizeM1;
2787 if (TTRes.BitMask)
2788 // BitMask is uint8_t which causes it to print the corresponding char.
2789 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2790 if (TTRes.InlineBits)
2791 Out << ", inlineBits: " << TTRes.InlineBits;
2793 Out << ")";
2796 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2797 Out << ", summary: (";
2798 printTypeTestResolution(TIS.TTRes);
2799 if (!TIS.WPDRes.empty()) {
2800 Out << ", wpdResolutions: (";
2801 FieldSeparator FS;
2802 for (auto &WPDRes : TIS.WPDRes) {
2803 Out << FS;
2804 Out << "(offset: " << WPDRes.first << ", ";
2805 printWPDRes(WPDRes.second);
2806 Out << ")";
2808 Out << ")";
2810 Out << ")";
2813 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
2814 const TypeIdCompatibleVtableInfo &TI) {
2815 Out << ", summary: (";
2816 FieldSeparator FS;
2817 for (auto &P : TI) {
2818 Out << FS;
2819 Out << "(offset: " << P.AddressPointOffset << ", ";
2820 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
2821 Out << ")";
2823 Out << ")";
2826 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2827 Out << "args: (";
2828 FieldSeparator FS;
2829 for (auto arg : Args) {
2830 Out << FS;
2831 Out << arg;
2833 Out << ")";
2836 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2837 Out << "wpdRes: (kind: ";
2838 Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2840 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2841 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2843 if (!WPDRes.ResByArg.empty()) {
2844 Out << ", resByArg: (";
2845 FieldSeparator FS;
2846 for (auto &ResByArg : WPDRes.ResByArg) {
2847 Out << FS;
2848 printArgs(ResByArg.first);
2849 Out << ", byArg: (kind: ";
2850 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2851 if (ResByArg.second.TheKind ==
2852 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2853 ResByArg.second.TheKind ==
2854 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2855 Out << ", info: " << ResByArg.second.Info;
2857 // The following fields are only used if the target does not support the
2858 // use of absolute symbols to store constants. Print only if non-zero.
2859 if (ResByArg.second.Byte || ResByArg.second.Bit)
2860 Out << ", byte: " << ResByArg.second.Byte
2861 << ", bit: " << ResByArg.second.Bit;
2863 Out << ")";
2865 Out << ")";
2867 Out << ")";
2870 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2871 switch (SK) {
2872 case GlobalValueSummary::AliasKind:
2873 return "alias";
2874 case GlobalValueSummary::FunctionKind:
2875 return "function";
2876 case GlobalValueSummary::GlobalVarKind:
2877 return "variable";
2879 llvm_unreachable("invalid summary kind");
2882 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2883 Out << ", aliasee: ";
2884 // The indexes emitted for distributed backends may not include the
2885 // aliasee summary (only if it is being imported directly). Handle
2886 // that case by just emitting "null" as the aliasee.
2887 if (AS->hasAliasee())
2888 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2889 else
2890 Out << "null";
2893 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2894 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
2895 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ")";
2897 auto VTableFuncs = GS->vTableFuncs();
2898 if (!VTableFuncs.empty()) {
2899 Out << ", vTableFuncs: (";
2900 FieldSeparator FS;
2901 for (auto &P : VTableFuncs) {
2902 Out << FS;
2903 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
2904 << ", offset: " << P.VTableOffset;
2905 Out << ")";
2907 Out << ")";
2911 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2912 switch (LT) {
2913 case GlobalValue::ExternalLinkage:
2914 return "external";
2915 case GlobalValue::PrivateLinkage:
2916 return "private";
2917 case GlobalValue::InternalLinkage:
2918 return "internal";
2919 case GlobalValue::LinkOnceAnyLinkage:
2920 return "linkonce";
2921 case GlobalValue::LinkOnceODRLinkage:
2922 return "linkonce_odr";
2923 case GlobalValue::WeakAnyLinkage:
2924 return "weak";
2925 case GlobalValue::WeakODRLinkage:
2926 return "weak_odr";
2927 case GlobalValue::CommonLinkage:
2928 return "common";
2929 case GlobalValue::AppendingLinkage:
2930 return "appending";
2931 case GlobalValue::ExternalWeakLinkage:
2932 return "extern_weak";
2933 case GlobalValue::AvailableExternallyLinkage:
2934 return "available_externally";
2936 llvm_unreachable("invalid linkage");
2939 // When printing the linkage types in IR where the ExternalLinkage is
2940 // not printed, and other linkage types are expected to be printed with
2941 // a space after the name.
2942 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2943 if (LT == GlobalValue::ExternalLinkage)
2944 return "";
2945 return getLinkageName(LT) + " ";
2948 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2949 Out << ", insts: " << FS->instCount();
2951 FunctionSummary::FFlags FFlags = FS->fflags();
2952 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2953 FFlags.ReturnDoesNotAlias) {
2954 Out << ", funcFlags: (";
2955 Out << "readNone: " << FFlags.ReadNone;
2956 Out << ", readOnly: " << FFlags.ReadOnly;
2957 Out << ", noRecurse: " << FFlags.NoRecurse;
2958 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2959 Out << ", noInline: " << FFlags.NoInline;
2960 Out << ")";
2962 if (!FS->calls().empty()) {
2963 Out << ", calls: (";
2964 FieldSeparator IFS;
2965 for (auto &Call : FS->calls()) {
2966 Out << IFS;
2967 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2968 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2969 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2970 else if (Call.second.RelBlockFreq)
2971 Out << ", relbf: " << Call.second.RelBlockFreq;
2972 Out << ")";
2974 Out << ")";
2977 if (const auto *TIdInfo = FS->getTypeIdInfo())
2978 printTypeIdInfo(*TIdInfo);
2981 void AssemblyWriter::printTypeIdInfo(
2982 const FunctionSummary::TypeIdInfo &TIDInfo) {
2983 Out << ", typeIdInfo: (";
2984 FieldSeparator TIDFS;
2985 if (!TIDInfo.TypeTests.empty()) {
2986 Out << TIDFS;
2987 Out << "typeTests: (";
2988 FieldSeparator FS;
2989 for (auto &GUID : TIDInfo.TypeTests) {
2990 auto TidIter = TheIndex->typeIds().equal_range(GUID);
2991 if (TidIter.first == TidIter.second) {
2992 Out << FS;
2993 Out << GUID;
2994 continue;
2996 // Print all type id that correspond to this GUID.
2997 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2998 Out << FS;
2999 auto Slot = Machine.getTypeIdSlot(It->second.first);
3000 assert(Slot != -1);
3001 Out << "^" << Slot;
3004 Out << ")";
3006 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3007 Out << TIDFS;
3008 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3010 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3011 Out << TIDFS;
3012 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3014 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3015 Out << TIDFS;
3016 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3017 "typeTestAssumeConstVCalls");
3019 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3020 Out << TIDFS;
3021 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3022 "typeCheckedLoadConstVCalls");
3024 Out << ")";
3027 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3028 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3029 if (TidIter.first == TidIter.second) {
3030 Out << "vFuncId: (";
3031 Out << "guid: " << VFId.GUID;
3032 Out << ", offset: " << VFId.Offset;
3033 Out << ")";
3034 return;
3036 // Print all type id that correspond to this GUID.
3037 FieldSeparator FS;
3038 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3039 Out << FS;
3040 Out << "vFuncId: (";
3041 auto Slot = Machine.getTypeIdSlot(It->second.first);
3042 assert(Slot != -1);
3043 Out << "^" << Slot;
3044 Out << ", offset: " << VFId.Offset;
3045 Out << ")";
3049 void AssemblyWriter::printNonConstVCalls(
3050 const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
3051 Out << Tag << ": (";
3052 FieldSeparator FS;
3053 for (auto &VFuncId : VCallList) {
3054 Out << FS;
3055 printVFuncId(VFuncId);
3057 Out << ")";
3060 void AssemblyWriter::printConstVCalls(
3061 const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3062 Out << Tag << ": (";
3063 FieldSeparator FS;
3064 for (auto &ConstVCall : VCallList) {
3065 Out << FS;
3066 Out << "(";
3067 printVFuncId(ConstVCall.VFunc);
3068 if (!ConstVCall.Args.empty()) {
3069 Out << ", ";
3070 printArgs(ConstVCall.Args);
3072 Out << ")";
3074 Out << ")";
3077 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3078 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3079 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3080 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3081 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3082 << ", flags: (";
3083 Out << "linkage: " << getLinkageName(LT);
3084 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3085 Out << ", live: " << GVFlags.Live;
3086 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3087 Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3088 Out << ")";
3090 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3091 printAliasSummary(cast<AliasSummary>(&Summary));
3092 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3093 printFunctionSummary(cast<FunctionSummary>(&Summary));
3094 else
3095 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3097 auto RefList = Summary.refs();
3098 if (!RefList.empty()) {
3099 Out << ", refs: (";
3100 FieldSeparator FS;
3101 for (auto &Ref : RefList) {
3102 Out << FS;
3103 if (Ref.isReadOnly())
3104 Out << "readonly ";
3105 else if (Ref.isWriteOnly())
3106 Out << "writeonly ";
3107 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3109 Out << ")";
3112 Out << ")";
3115 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3116 Out << "^" << Slot << " = gv: (";
3117 if (!VI.name().empty())
3118 Out << "name: \"" << VI.name() << "\"";
3119 else
3120 Out << "guid: " << VI.getGUID();
3121 if (!VI.getSummaryList().empty()) {
3122 Out << ", summaries: (";
3123 FieldSeparator FS;
3124 for (auto &Summary : VI.getSummaryList()) {
3125 Out << FS;
3126 printSummary(*Summary);
3128 Out << ")";
3130 Out << ")";
3131 if (!VI.name().empty())
3132 Out << " ; guid = " << VI.getGUID();
3133 Out << "\n";
3136 static void printMetadataIdentifier(StringRef Name,
3137 formatted_raw_ostream &Out) {
3138 if (Name.empty()) {
3139 Out << "<empty name> ";
3140 } else {
3141 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3142 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3143 Out << Name[0];
3144 else
3145 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3146 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3147 unsigned char C = Name[i];
3148 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3149 C == '.' || C == '_')
3150 Out << C;
3151 else
3152 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3157 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3158 Out << '!';
3159 printMetadataIdentifier(NMD->getName(), Out);
3160 Out << " = !{";
3161 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3162 if (i)
3163 Out << ", ";
3165 // Write DIExpressions inline.
3166 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3167 MDNode *Op = NMD->getOperand(i);
3168 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3169 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3170 continue;
3173 int Slot = Machine.getMetadataSlot(Op);
3174 if (Slot == -1)
3175 Out << "<badref>";
3176 else
3177 Out << '!' << Slot;
3179 Out << "}\n";
3182 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3183 formatted_raw_ostream &Out) {
3184 switch (Vis) {
3185 case GlobalValue::DefaultVisibility: break;
3186 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3187 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3191 static void PrintDSOLocation(const GlobalValue &GV,
3192 formatted_raw_ostream &Out) {
3193 // GVs with local linkage or non default visibility are implicitly dso_local,
3194 // so we don't print it.
3195 bool Implicit = GV.hasLocalLinkage() ||
3196 (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3197 if (GV.isDSOLocal() && !Implicit)
3198 Out << "dso_local ";
3201 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3202 formatted_raw_ostream &Out) {
3203 switch (SCT) {
3204 case GlobalValue::DefaultStorageClass: break;
3205 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3206 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3210 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3211 formatted_raw_ostream &Out) {
3212 switch (TLM) {
3213 case GlobalVariable::NotThreadLocal:
3214 break;
3215 case GlobalVariable::GeneralDynamicTLSModel:
3216 Out << "thread_local ";
3217 break;
3218 case GlobalVariable::LocalDynamicTLSModel:
3219 Out << "thread_local(localdynamic) ";
3220 break;
3221 case GlobalVariable::InitialExecTLSModel:
3222 Out << "thread_local(initialexec) ";
3223 break;
3224 case GlobalVariable::LocalExecTLSModel:
3225 Out << "thread_local(localexec) ";
3226 break;
3230 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3231 switch (UA) {
3232 case GlobalVariable::UnnamedAddr::None:
3233 return "";
3234 case GlobalVariable::UnnamedAddr::Local:
3235 return "local_unnamed_addr";
3236 case GlobalVariable::UnnamedAddr::Global:
3237 return "unnamed_addr";
3239 llvm_unreachable("Unknown UnnamedAddr");
3242 static void maybePrintComdat(formatted_raw_ostream &Out,
3243 const GlobalObject &GO) {
3244 const Comdat *C = GO.getComdat();
3245 if (!C)
3246 return;
3248 if (isa<GlobalVariable>(GO))
3249 Out << ',';
3250 Out << " comdat";
3252 if (GO.getName() == C->getName())
3253 return;
3255 Out << '(';
3256 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3257 Out << ')';
3260 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3261 if (GV->isMaterializable())
3262 Out << "; Materializable\n";
3264 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3265 Out << " = ";
3267 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3268 Out << "external ";
3270 Out << getLinkageNameWithSpace(GV->getLinkage());
3271 PrintDSOLocation(*GV, Out);
3272 PrintVisibility(GV->getVisibility(), Out);
3273 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3274 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3275 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3276 if (!UA.empty())
3277 Out << UA << ' ';
3279 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3280 Out << "addrspace(" << AddressSpace << ") ";
3281 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3282 Out << (GV->isConstant() ? "constant " : "global ");
3283 TypePrinter.print(GV->getValueType(), Out);
3285 if (GV->hasInitializer()) {
3286 Out << ' ';
3287 writeOperand(GV->getInitializer(), false);
3290 if (GV->hasSection()) {
3291 Out << ", section \"";
3292 printEscapedString(GV->getSection(), Out);
3293 Out << '"';
3295 if (GV->hasPartition()) {
3296 Out << ", partition \"";
3297 printEscapedString(GV->getPartition(), Out);
3298 Out << '"';
3301 maybePrintComdat(Out, *GV);
3302 if (GV->getAlignment())
3303 Out << ", align " << GV->getAlignment();
3305 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3306 GV->getAllMetadata(MDs);
3307 printMetadataAttachments(MDs, ", ");
3309 auto Attrs = GV->getAttributes();
3310 if (Attrs.hasAttributes())
3311 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3313 printInfoComment(*GV);
3316 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3317 if (GIS->isMaterializable())
3318 Out << "; Materializable\n";
3320 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3321 Out << " = ";
3323 Out << getLinkageNameWithSpace(GIS->getLinkage());
3324 PrintDSOLocation(*GIS, Out);
3325 PrintVisibility(GIS->getVisibility(), Out);
3326 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3327 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3328 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3329 if (!UA.empty())
3330 Out << UA << ' ';
3332 if (isa<GlobalAlias>(GIS))
3333 Out << "alias ";
3334 else if (isa<GlobalIFunc>(GIS))
3335 Out << "ifunc ";
3336 else
3337 llvm_unreachable("Not an alias or ifunc!");
3339 TypePrinter.print(GIS->getValueType(), Out);
3341 Out << ", ";
3343 const Constant *IS = GIS->getIndirectSymbol();
3345 if (!IS) {
3346 TypePrinter.print(GIS->getType(), Out);
3347 Out << " <<NULL ALIASEE>>";
3348 } else {
3349 writeOperand(IS, !isa<ConstantExpr>(IS));
3352 if (GIS->hasPartition()) {
3353 Out << ", partition \"";
3354 printEscapedString(GIS->getPartition(), Out);
3355 Out << '"';
3358 printInfoComment(*GIS);
3359 Out << '\n';
3362 void AssemblyWriter::printComdat(const Comdat *C) {
3363 C->print(Out);
3366 void AssemblyWriter::printTypeIdentities() {
3367 if (TypePrinter.empty())
3368 return;
3370 Out << '\n';
3372 // Emit all numbered types.
3373 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3374 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3375 Out << '%' << I << " = type ";
3377 // Make sure we print out at least one level of the type structure, so
3378 // that we do not get %2 = type %2
3379 TypePrinter.printStructBody(NumberedTypes[I], Out);
3380 Out << '\n';
3383 auto &NamedTypes = TypePrinter.getNamedTypes();
3384 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3385 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3386 Out << " = type ";
3388 // Make sure we print out at least one level of the type structure, so
3389 // that we do not get %FILE = type %FILE
3390 TypePrinter.printStructBody(NamedTypes[I], Out);
3391 Out << '\n';
3395 /// printFunction - Print all aspects of a function.
3396 void AssemblyWriter::printFunction(const Function *F) {
3397 // Print out the return type and name.
3398 Out << '\n';
3400 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3402 if (F->isMaterializable())
3403 Out << "; Materializable\n";
3405 const AttributeList &Attrs = F->getAttributes();
3406 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3407 AttributeSet AS = Attrs.getFnAttributes();
3408 std::string AttrStr;
3410 for (const Attribute &Attr : AS) {
3411 if (!Attr.isStringAttribute()) {
3412 if (!AttrStr.empty()) AttrStr += ' ';
3413 AttrStr += Attr.getAsString();
3417 if (!AttrStr.empty())
3418 Out << "; Function Attrs: " << AttrStr << '\n';
3421 Machine.incorporateFunction(F);
3423 if (F->isDeclaration()) {
3424 Out << "declare";
3425 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3426 F->getAllMetadata(MDs);
3427 printMetadataAttachments(MDs, " ");
3428 Out << ' ';
3429 } else
3430 Out << "define ";
3432 Out << getLinkageNameWithSpace(F->getLinkage());
3433 PrintDSOLocation(*F, Out);
3434 PrintVisibility(F->getVisibility(), Out);
3435 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3437 // Print the calling convention.
3438 if (F->getCallingConv() != CallingConv::C) {
3439 PrintCallingConv(F->getCallingConv(), Out);
3440 Out << " ";
3443 FunctionType *FT = F->getFunctionType();
3444 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3445 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3446 TypePrinter.print(F->getReturnType(), Out);
3447 Out << ' ';
3448 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3449 Out << '(';
3451 // Loop over the arguments, printing them...
3452 if (F->isDeclaration() && !IsForDebug) {
3453 // We're only interested in the type here - don't print argument names.
3454 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3455 // Insert commas as we go... the first arg doesn't get a comma
3456 if (I)
3457 Out << ", ";
3458 // Output type...
3459 TypePrinter.print(FT->getParamType(I), Out);
3461 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3462 if (ArgAttrs.hasAttributes())
3463 Out << ' ' << ArgAttrs.getAsString();
3465 } else {
3466 // The arguments are meaningful here, print them in detail.
3467 for (const Argument &Arg : F->args()) {
3468 // Insert commas as we go... the first arg doesn't get a comma
3469 if (Arg.getArgNo() != 0)
3470 Out << ", ";
3471 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3475 // Finish printing arguments...
3476 if (FT->isVarArg()) {
3477 if (FT->getNumParams()) Out << ", ";
3478 Out << "..."; // Output varargs portion of signature!
3480 Out << ')';
3481 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3482 if (!UA.empty())
3483 Out << ' ' << UA;
3484 // We print the function address space if it is non-zero or if we are writing
3485 // a module with a non-zero program address space or if there is no valid
3486 // Module* so that the file can be parsed without the datalayout string.
3487 const Module *Mod = F->getParent();
3488 if (F->getAddressSpace() != 0 || !Mod ||
3489 Mod->getDataLayout().getProgramAddressSpace() != 0)
3490 Out << " addrspace(" << F->getAddressSpace() << ")";
3491 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3492 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3493 if (F->hasSection()) {
3494 Out << " section \"";
3495 printEscapedString(F->getSection(), Out);
3496 Out << '"';
3498 if (F->hasPartition()) {
3499 Out << " partition \"";
3500 printEscapedString(F->getPartition(), Out);
3501 Out << '"';
3503 maybePrintComdat(Out, *F);
3504 if (F->getAlignment())
3505 Out << " align " << F->getAlignment();
3506 if (F->hasGC())
3507 Out << " gc \"" << F->getGC() << '"';
3508 if (F->hasPrefixData()) {
3509 Out << " prefix ";
3510 writeOperand(F->getPrefixData(), true);
3512 if (F->hasPrologueData()) {
3513 Out << " prologue ";
3514 writeOperand(F->getPrologueData(), true);
3516 if (F->hasPersonalityFn()) {
3517 Out << " personality ";
3518 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3521 if (F->isDeclaration()) {
3522 Out << '\n';
3523 } else {
3524 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3525 F->getAllMetadata(MDs);
3526 printMetadataAttachments(MDs, " ");
3528 Out << " {";
3529 // Output all of the function's basic blocks.
3530 for (const BasicBlock &BB : *F)
3531 printBasicBlock(&BB);
3533 // Output the function's use-lists.
3534 printUseLists(F);
3536 Out << "}\n";
3539 Machine.purgeFunction();
3542 /// printArgument - This member is called for every argument that is passed into
3543 /// the function. Simply print it out
3544 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3545 // Output type...
3546 TypePrinter.print(Arg->getType(), Out);
3548 // Output parameter attributes list
3549 if (Attrs.hasAttributes())
3550 Out << ' ' << Attrs.getAsString();
3552 // Output name, if available...
3553 if (Arg->hasName()) {
3554 Out << ' ';
3555 PrintLLVMName(Out, Arg);
3556 } else {
3557 int Slot = Machine.getLocalSlot(Arg);
3558 assert(Slot != -1 && "expect argument in function here");
3559 Out << " %" << Slot;
3563 /// printBasicBlock - This member is called for each basic block in a method.
3564 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3565 bool IsEntryBlock = BB == &BB->getParent()->getEntryBlock();
3566 if (BB->hasName()) { // Print out the label if it exists...
3567 Out << "\n";
3568 PrintLLVMName(Out, BB->getName(), LabelPrefix);
3569 Out << ':';
3570 } else if (!IsEntryBlock) {
3571 Out << "\n";
3572 int Slot = Machine.getLocalSlot(BB);
3573 if (Slot != -1)
3574 Out << Slot << ":";
3575 else
3576 Out << "<badref>:";
3579 if (!BB->getParent()) {
3580 Out.PadToColumn(50);
3581 Out << "; Error: Block without parent!";
3582 } else if (!IsEntryBlock) {
3583 // Output predecessors for the block.
3584 Out.PadToColumn(50);
3585 Out << ";";
3586 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3588 if (PI == PE) {
3589 Out << " No predecessors!";
3590 } else {
3591 Out << " preds = ";
3592 writeOperand(*PI, false);
3593 for (++PI; PI != PE; ++PI) {
3594 Out << ", ";
3595 writeOperand(*PI, false);
3600 Out << "\n";
3602 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3604 // Output all of the instructions in the basic block...
3605 for (const Instruction &I : *BB) {
3606 printInstructionLine(I);
3609 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3612 /// printInstructionLine - Print an instruction and a newline character.
3613 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3614 printInstruction(I);
3615 Out << '\n';
3618 /// printGCRelocateComment - print comment after call to the gc.relocate
3619 /// intrinsic indicating base and derived pointer names.
3620 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3621 Out << " ; (";
3622 writeOperand(Relocate.getBasePtr(), false);
3623 Out << ", ";
3624 writeOperand(Relocate.getDerivedPtr(), false);
3625 Out << ")";
3628 /// printInfoComment - Print a little comment after the instruction indicating
3629 /// which slot it occupies.
3630 void AssemblyWriter::printInfoComment(const Value &V) {
3631 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3632 printGCRelocateComment(*Relocate);
3634 if (AnnotationWriter)
3635 AnnotationWriter->printInfoComment(V, Out);
3638 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3639 raw_ostream &Out) {
3640 // We print the address space of the call if it is non-zero.
3641 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3642 bool PrintAddrSpace = CallAddrSpace != 0;
3643 if (!PrintAddrSpace) {
3644 const Module *Mod = getModuleFromVal(I);
3645 // We also print it if it is zero but not equal to the program address space
3646 // or if we can't find a valid Module* to make it possible to parse
3647 // the resulting file even without a datalayout string.
3648 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3649 PrintAddrSpace = true;
3651 if (PrintAddrSpace)
3652 Out << " addrspace(" << CallAddrSpace << ")";
3655 // This member is called for each Instruction in a function..
3656 void AssemblyWriter::printInstruction(const Instruction &I) {
3657 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3659 // Print out indentation for an instruction.
3660 Out << " ";
3662 // Print out name if it exists...
3663 if (I.hasName()) {
3664 PrintLLVMName(Out, &I);
3665 Out << " = ";
3666 } else if (!I.getType()->isVoidTy()) {
3667 // Print out the def slot taken.
3668 int SlotNum = Machine.getLocalSlot(&I);
3669 if (SlotNum == -1)
3670 Out << "<badref> = ";
3671 else
3672 Out << '%' << SlotNum << " = ";
3675 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3676 if (CI->isMustTailCall())
3677 Out << "musttail ";
3678 else if (CI->isTailCall())
3679 Out << "tail ";
3680 else if (CI->isNoTailCall())
3681 Out << "notail ";
3684 // Print out the opcode...
3685 Out << I.getOpcodeName();
3687 // If this is an atomic load or store, print out the atomic marker.
3688 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
3689 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3690 Out << " atomic";
3692 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3693 Out << " weak";
3695 // If this is a volatile operation, print out the volatile marker.
3696 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
3697 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3698 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3699 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3700 Out << " volatile";
3702 // Print out optimization information.
3703 WriteOptimizationInfo(Out, &I);
3705 // Print out the compare instruction predicates
3706 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3707 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3709 // Print out the atomicrmw operation
3710 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3711 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3713 // Print out the type of the operands...
3714 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3716 // Special case conditional branches to swizzle the condition out to the front
3717 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3718 const BranchInst &BI(cast<BranchInst>(I));
3719 Out << ' ';
3720 writeOperand(BI.getCondition(), true);
3721 Out << ", ";
3722 writeOperand(BI.getSuccessor(0), true);
3723 Out << ", ";
3724 writeOperand(BI.getSuccessor(1), true);
3726 } else if (isa<SwitchInst>(I)) {
3727 const SwitchInst& SI(cast<SwitchInst>(I));
3728 // Special case switch instruction to get formatting nice and correct.
3729 Out << ' ';
3730 writeOperand(SI.getCondition(), true);
3731 Out << ", ";
3732 writeOperand(SI.getDefaultDest(), true);
3733 Out << " [";
3734 for (auto Case : SI.cases()) {
3735 Out << "\n ";
3736 writeOperand(Case.getCaseValue(), true);
3737 Out << ", ";
3738 writeOperand(Case.getCaseSuccessor(), true);
3740 Out << "\n ]";
3741 } else if (isa<IndirectBrInst>(I)) {
3742 // Special case indirectbr instruction to get formatting nice and correct.
3743 Out << ' ';
3744 writeOperand(Operand, true);
3745 Out << ", [";
3747 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3748 if (i != 1)
3749 Out << ", ";
3750 writeOperand(I.getOperand(i), true);
3752 Out << ']';
3753 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3754 Out << ' ';
3755 TypePrinter.print(I.getType(), Out);
3756 Out << ' ';
3758 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3759 if (op) Out << ", ";
3760 Out << "[ ";
3761 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3762 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3764 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3765 Out << ' ';
3766 writeOperand(I.getOperand(0), true);
3767 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3768 Out << ", " << *i;
3769 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3770 Out << ' ';
3771 writeOperand(I.getOperand(0), true); Out << ", ";
3772 writeOperand(I.getOperand(1), true);
3773 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3774 Out << ", " << *i;
3775 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3776 Out << ' ';
3777 TypePrinter.print(I.getType(), Out);
3778 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3779 Out << '\n';
3781 if (LPI->isCleanup())
3782 Out << " cleanup";
3784 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3785 if (i != 0 || LPI->isCleanup()) Out << "\n";
3786 if (LPI->isCatch(i))
3787 Out << " catch ";
3788 else
3789 Out << " filter ";
3791 writeOperand(LPI->getClause(i), true);
3793 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3794 Out << " within ";
3795 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3796 Out << " [";
3797 unsigned Op = 0;
3798 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3799 if (Op > 0)
3800 Out << ", ";
3801 writeOperand(PadBB, /*PrintType=*/true);
3802 ++Op;
3804 Out << "] unwind ";
3805 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3806 writeOperand(UnwindDest, /*PrintType=*/true);
3807 else
3808 Out << "to caller";
3809 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3810 Out << " within ";
3811 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3812 Out << " [";
3813 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3814 ++Op) {
3815 if (Op > 0)
3816 Out << ", ";
3817 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3819 Out << ']';
3820 } else if (isa<ReturnInst>(I) && !Operand) {
3821 Out << " void";
3822 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3823 Out << " from ";
3824 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3826 Out << " to ";
3827 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3828 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3829 Out << " from ";
3830 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3832 Out << " unwind ";
3833 if (CRI->hasUnwindDest())
3834 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3835 else
3836 Out << "to caller";
3837 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3838 // Print the calling convention being used.
3839 if (CI->getCallingConv() != CallingConv::C) {
3840 Out << " ";
3841 PrintCallingConv(CI->getCallingConv(), Out);
3844 Operand = CI->getCalledValue();
3845 FunctionType *FTy = CI->getFunctionType();
3846 Type *RetTy = FTy->getReturnType();
3847 const AttributeList &PAL = CI->getAttributes();
3849 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3850 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3852 // Only print addrspace(N) if necessary:
3853 maybePrintCallAddrSpace(Operand, &I, Out);
3855 // If possible, print out the short form of the call instruction. We can
3856 // only do this if the first argument is a pointer to a nonvararg function,
3857 // and if the return type is not a pointer to a function.
3859 Out << ' ';
3860 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3861 Out << ' ';
3862 writeOperand(Operand, false);
3863 Out << '(';
3864 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3865 if (op > 0)
3866 Out << ", ";
3867 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3870 // Emit an ellipsis if this is a musttail call in a vararg function. This
3871 // is only to aid readability, musttail calls forward varargs by default.
3872 if (CI->isMustTailCall() && CI->getParent() &&
3873 CI->getParent()->getParent() &&
3874 CI->getParent()->getParent()->isVarArg())
3875 Out << ", ...";
3877 Out << ')';
3878 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3879 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3881 writeOperandBundles(CI);
3882 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3883 Operand = II->getCalledValue();
3884 FunctionType *FTy = II->getFunctionType();
3885 Type *RetTy = FTy->getReturnType();
3886 const AttributeList &PAL = II->getAttributes();
3888 // Print the calling convention being used.
3889 if (II->getCallingConv() != CallingConv::C) {
3890 Out << " ";
3891 PrintCallingConv(II->getCallingConv(), Out);
3894 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3895 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3897 // Only print addrspace(N) if necessary:
3898 maybePrintCallAddrSpace(Operand, &I, Out);
3900 // If possible, print out the short form of the invoke instruction. We can
3901 // only do this if the first argument is a pointer to a nonvararg function,
3902 // and if the return type is not a pointer to a function.
3904 Out << ' ';
3905 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3906 Out << ' ';
3907 writeOperand(Operand, false);
3908 Out << '(';
3909 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3910 if (op)
3911 Out << ", ";
3912 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3915 Out << ')';
3916 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3917 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3919 writeOperandBundles(II);
3921 Out << "\n to ";
3922 writeOperand(II->getNormalDest(), true);
3923 Out << " unwind ";
3924 writeOperand(II->getUnwindDest(), true);
3925 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
3926 Operand = CBI->getCalledValue();
3927 FunctionType *FTy = CBI->getFunctionType();
3928 Type *RetTy = FTy->getReturnType();
3929 const AttributeList &PAL = CBI->getAttributes();
3931 // Print the calling convention being used.
3932 if (CBI->getCallingConv() != CallingConv::C) {
3933 Out << " ";
3934 PrintCallingConv(CBI->getCallingConv(), Out);
3937 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3938 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3940 // If possible, print out the short form of the callbr instruction. We can
3941 // only do this if the first argument is a pointer to a nonvararg function,
3942 // and if the return type is not a pointer to a function.
3944 Out << ' ';
3945 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3946 Out << ' ';
3947 writeOperand(Operand, false);
3948 Out << '(';
3949 for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) {
3950 if (op)
3951 Out << ", ";
3952 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op));
3955 Out << ')';
3956 if (PAL.hasAttributes(AttributeList::FunctionIndex))
3957 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3959 writeOperandBundles(CBI);
3961 Out << "\n to ";
3962 writeOperand(CBI->getDefaultDest(), true);
3963 Out << " [";
3964 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
3965 if (i != 0)
3966 Out << ", ";
3967 writeOperand(CBI->getIndirectDest(i), true);
3969 Out << ']';
3970 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3971 Out << ' ';
3972 if (AI->isUsedWithInAlloca())
3973 Out << "inalloca ";
3974 if (AI->isSwiftError())
3975 Out << "swifterror ";
3976 TypePrinter.print(AI->getAllocatedType(), Out);
3978 // Explicitly write the array size if the code is broken, if it's an array
3979 // allocation, or if the type is not canonical for scalar allocations. The
3980 // latter case prevents the type from mutating when round-tripping through
3981 // assembly.
3982 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3983 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3984 Out << ", ";
3985 writeOperand(AI->getArraySize(), true);
3987 if (AI->getAlignment()) {
3988 Out << ", align " << AI->getAlignment();
3991 unsigned AddrSpace = AI->getType()->getAddressSpace();
3992 if (AddrSpace != 0) {
3993 Out << ", addrspace(" << AddrSpace << ')';
3995 } else if (isa<CastInst>(I)) {
3996 if (Operand) {
3997 Out << ' ';
3998 writeOperand(Operand, true); // Work with broken code
4000 Out << " to ";
4001 TypePrinter.print(I.getType(), Out);
4002 } else if (isa<VAArgInst>(I)) {
4003 if (Operand) {
4004 Out << ' ';
4005 writeOperand(Operand, true); // Work with broken code
4007 Out << ", ";
4008 TypePrinter.print(I.getType(), Out);
4009 } else if (Operand) { // Print the normal way.
4010 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4011 Out << ' ';
4012 TypePrinter.print(GEP->getSourceElementType(), Out);
4013 Out << ',';
4014 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4015 Out << ' ';
4016 TypePrinter.print(LI->getType(), Out);
4017 Out << ',';
4020 // PrintAllTypes - Instructions who have operands of all the same type
4021 // omit the type from all but the first operand. If the instruction has
4022 // different type operands (for example br), then they are all printed.
4023 bool PrintAllTypes = false;
4024 Type *TheType = Operand->getType();
4026 // Select, Store and ShuffleVector always print all types.
4027 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
4028 || isa<ReturnInst>(I)) {
4029 PrintAllTypes = true;
4030 } else {
4031 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4032 Operand = I.getOperand(i);
4033 // note that Operand shouldn't be null, but the test helps make dump()
4034 // more tolerant of malformed IR
4035 if (Operand && Operand->getType() != TheType) {
4036 PrintAllTypes = true; // We have differing types! Print them all!
4037 break;
4042 if (!PrintAllTypes) {
4043 Out << ' ';
4044 TypePrinter.print(TheType, Out);
4047 Out << ' ';
4048 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4049 if (i) Out << ", ";
4050 writeOperand(I.getOperand(i), PrintAllTypes);
4054 // Print atomic ordering/alignment for memory operations
4055 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4056 if (LI->isAtomic())
4057 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4058 if (LI->getAlignment())
4059 Out << ", align " << LI->getAlignment();
4060 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4061 if (SI->isAtomic())
4062 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4063 if (SI->getAlignment())
4064 Out << ", align " << SI->getAlignment();
4065 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4066 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4067 CXI->getFailureOrdering(), CXI->getSyncScopeID());
4068 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4069 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4070 RMWI->getSyncScopeID());
4071 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4072 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4075 // Print Metadata info.
4076 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4077 I.getAllMetadata(InstMD);
4078 printMetadataAttachments(InstMD, ", ");
4080 // Print a nice comment.
4081 printInfoComment(I);
4084 void AssemblyWriter::printMetadataAttachments(
4085 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4086 StringRef Separator) {
4087 if (MDs.empty())
4088 return;
4090 if (MDNames.empty())
4091 MDs[0].second->getContext().getMDKindNames(MDNames);
4093 for (const auto &I : MDs) {
4094 unsigned Kind = I.first;
4095 Out << Separator;
4096 if (Kind < MDNames.size()) {
4097 Out << "!";
4098 printMetadataIdentifier(MDNames[Kind], Out);
4099 } else
4100 Out << "!<unknown kind #" << Kind << ">";
4101 Out << ' ';
4102 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
4106 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4107 Out << '!' << Slot << " = ";
4108 printMDNodeBody(Node);
4109 Out << "\n";
4112 void AssemblyWriter::writeAllMDNodes() {
4113 SmallVector<const MDNode *, 16> Nodes;
4114 Nodes.resize(Machine.mdn_size());
4115 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
4116 I != E; ++I)
4117 Nodes[I->second] = cast<MDNode>(I->first);
4119 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4120 writeMDNode(i, Nodes[i]);
4124 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4125 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
4128 void AssemblyWriter::writeAllAttributeGroups() {
4129 std::vector<std::pair<AttributeSet, unsigned>> asVec;
4130 asVec.resize(Machine.as_size());
4132 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4133 I != E; ++I)
4134 asVec[I->second] = *I;
4136 for (const auto &I : asVec)
4137 Out << "attributes #" << I.second << " = { "
4138 << I.first.getAsString(true) << " }\n";
4141 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4142 bool IsInFunction = Machine.getFunction();
4143 if (IsInFunction)
4144 Out << " ";
4146 Out << "uselistorder";
4147 if (const BasicBlock *BB =
4148 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4149 Out << "_bb ";
4150 writeOperand(BB->getParent(), false);
4151 Out << ", ";
4152 writeOperand(BB, false);
4153 } else {
4154 Out << " ";
4155 writeOperand(Order.V, true);
4157 Out << ", { ";
4159 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4160 Out << Order.Shuffle[0];
4161 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4162 Out << ", " << Order.Shuffle[I];
4163 Out << " }\n";
4166 void AssemblyWriter::printUseLists(const Function *F) {
4167 auto hasMore =
4168 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4169 if (!hasMore())
4170 // Nothing to do.
4171 return;
4173 Out << "\n; uselistorder directives\n";
4174 while (hasMore()) {
4175 printUseListOrder(UseListOrders.back());
4176 UseListOrders.pop_back();
4180 //===----------------------------------------------------------------------===//
4181 // External Interface declarations
4182 //===----------------------------------------------------------------------===//
4184 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4185 bool ShouldPreserveUseListOrder,
4186 bool IsForDebug) const {
4187 SlotTracker SlotTable(this->getParent());
4188 formatted_raw_ostream OS(ROS);
4189 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4190 IsForDebug,
4191 ShouldPreserveUseListOrder);
4192 W.printFunction(this);
4195 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4196 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4197 SlotTracker SlotTable(this);
4198 formatted_raw_ostream OS(ROS);
4199 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4200 ShouldPreserveUseListOrder);
4201 W.printModule(this);
4204 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4205 SlotTracker SlotTable(getParent());
4206 formatted_raw_ostream OS(ROS);
4207 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4208 W.printNamedMDNode(this);
4211 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4212 bool IsForDebug) const {
4213 Optional<SlotTracker> LocalST;
4214 SlotTracker *SlotTable;
4215 if (auto *ST = MST.getMachine())
4216 SlotTable = ST;
4217 else {
4218 LocalST.emplace(getParent());
4219 SlotTable = &*LocalST;
4222 formatted_raw_ostream OS(ROS);
4223 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4224 W.printNamedMDNode(this);
4227 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4228 PrintLLVMName(ROS, getName(), ComdatPrefix);
4229 ROS << " = comdat ";
4231 switch (getSelectionKind()) {
4232 case Comdat::Any:
4233 ROS << "any";
4234 break;
4235 case Comdat::ExactMatch:
4236 ROS << "exactmatch";
4237 break;
4238 case Comdat::Largest:
4239 ROS << "largest";
4240 break;
4241 case Comdat::NoDuplicates:
4242 ROS << "noduplicates";
4243 break;
4244 case Comdat::SameSize:
4245 ROS << "samesize";
4246 break;
4249 ROS << '\n';
4252 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4253 TypePrinting TP;
4254 TP.print(const_cast<Type*>(this), OS);
4256 if (NoDetails)
4257 return;
4259 // If the type is a named struct type, print the body as well.
4260 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4261 if (!STy->isLiteral()) {
4262 OS << " = type ";
4263 TP.printStructBody(STy, OS);
4267 static bool isReferencingMDNode(const Instruction &I) {
4268 if (const auto *CI = dyn_cast<CallInst>(&I))
4269 if (Function *F = CI->getCalledFunction())
4270 if (F->isIntrinsic())
4271 for (auto &Op : I.operands())
4272 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4273 if (isa<MDNode>(V->getMetadata()))
4274 return true;
4275 return false;
4278 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4279 bool ShouldInitializeAllMetadata = false;
4280 if (auto *I = dyn_cast<Instruction>(this))
4281 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4282 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4283 ShouldInitializeAllMetadata = true;
4285 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4286 print(ROS, MST, IsForDebug);
4289 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4290 bool IsForDebug) const {
4291 formatted_raw_ostream OS(ROS);
4292 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4293 SlotTracker &SlotTable =
4294 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4295 auto incorporateFunction = [&](const Function *F) {
4296 if (F)
4297 MST.incorporateFunction(*F);
4300 if (const Instruction *I = dyn_cast<Instruction>(this)) {
4301 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4302 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4303 W.printInstruction(*I);
4304 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4305 incorporateFunction(BB->getParent());
4306 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4307 W.printBasicBlock(BB);
4308 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4309 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4310 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4311 W.printGlobal(V);
4312 else if (const Function *F = dyn_cast<Function>(GV))
4313 W.printFunction(F);
4314 else
4315 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4316 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4317 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4318 } else if (const Constant *C = dyn_cast<Constant>(this)) {
4319 TypePrinting TypePrinter;
4320 TypePrinter.print(C->getType(), OS);
4321 OS << ' ';
4322 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4323 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4324 this->printAsOperand(OS, /* PrintType */ true, MST);
4325 } else {
4326 llvm_unreachable("Unknown value to print out!");
4330 /// Print without a type, skipping the TypePrinting object.
4332 /// \return \c true iff printing was successful.
4333 static bool printWithoutType(const Value &V, raw_ostream &O,
4334 SlotTracker *Machine, const Module *M) {
4335 if (V.hasName() || isa<GlobalValue>(V) ||
4336 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4337 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4338 return true;
4340 return false;
4343 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4344 ModuleSlotTracker &MST) {
4345 TypePrinting TypePrinter(MST.getModule());
4346 if (PrintType) {
4347 TypePrinter.print(V.getType(), O);
4348 O << ' ';
4351 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4352 MST.getModule());
4355 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4356 const Module *M) const {
4357 if (!M)
4358 M = getModuleFromVal(this);
4360 if (!PrintType)
4361 if (printWithoutType(*this, O, nullptr, M))
4362 return;
4364 SlotTracker Machine(
4365 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4366 ModuleSlotTracker MST(Machine, M);
4367 printAsOperandImpl(*this, O, PrintType, MST);
4370 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4371 ModuleSlotTracker &MST) const {
4372 if (!PrintType)
4373 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4374 return;
4376 printAsOperandImpl(*this, O, PrintType, MST);
4379 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4380 ModuleSlotTracker &MST, const Module *M,
4381 bool OnlyAsOperand) {
4382 formatted_raw_ostream OS(ROS);
4384 TypePrinting TypePrinter(M);
4386 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4387 /* FromValue */ true);
4389 auto *N = dyn_cast<MDNode>(&MD);
4390 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4391 return;
4393 OS << " = ";
4394 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4397 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4398 ModuleSlotTracker MST(M, isa<MDNode>(this));
4399 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4402 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4403 const Module *M) const {
4404 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4407 void Metadata::print(raw_ostream &OS, const Module *M,
4408 bool /*IsForDebug*/) const {
4409 ModuleSlotTracker MST(M, isa<MDNode>(this));
4410 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4413 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4414 const Module *M, bool /*IsForDebug*/) const {
4415 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4418 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4419 SlotTracker SlotTable(this);
4420 formatted_raw_ostream OS(ROS);
4421 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4422 W.printModuleSummaryIndex();
4425 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4426 // Value::dump - allow easy printing of Values from the debugger.
4427 LLVM_DUMP_METHOD
4428 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4430 // Type::dump - allow easy printing of Types from the debugger.
4431 LLVM_DUMP_METHOD
4432 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4434 // Module::dump() - Allow printing of Modules from the debugger.
4435 LLVM_DUMP_METHOD
4436 void Module::dump() const {
4437 print(dbgs(), nullptr,
4438 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4441 // Allow printing of Comdats from the debugger.
4442 LLVM_DUMP_METHOD
4443 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4445 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4446 LLVM_DUMP_METHOD
4447 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4449 LLVM_DUMP_METHOD
4450 void Metadata::dump() const { dump(nullptr); }
4452 LLVM_DUMP_METHOD
4453 void Metadata::dump(const Module *M) const {
4454 print(dbgs(), M, /*IsForDebug=*/true);
4455 dbgs() << '\n';
4458 // Allow printing of ModuleSummaryIndex from the debugger.
4459 LLVM_DUMP_METHOD
4460 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4461 #endif