Coverage Report

Created: 2024-01-17 10:31

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