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