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