Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGDebugInfo.h"
14
#include "CGBlocks.h"
15
#include "CGCXXABI.h"
16
#include "CGObjCRuntime.h"
17
#include "CGRecordLayout.h"
18
#include "CodeGenFunction.h"
19
#include "CodeGenModule.h"
20
#include "ConstantEmitter.h"
21
#include "clang/AST/ASTContext.h"
22
#include "clang/AST/Attr.h"
23
#include "clang/AST/DeclFriend.h"
24
#include "clang/AST/DeclObjC.h"
25
#include "clang/AST/DeclTemplate.h"
26
#include "clang/AST/Expr.h"
27
#include "clang/AST/RecordLayout.h"
28
#include "clang/Basic/CodeGenOptions.h"
29
#include "clang/Basic/FileManager.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/Version.h"
32
#include "clang/Frontend/FrontendOptions.h"
33
#include "clang/Lex/HeaderSearchOptions.h"
34
#include "clang/Lex/ModuleMap.h"
35
#include "clang/Lex/PreprocessorOptions.h"
36
#include "llvm/ADT/DenseSet.h"
37
#include "llvm/ADT/SmallVector.h"
38
#include "llvm/ADT/StringExtras.h"
39
#include "llvm/IR/Constants.h"
40
#include "llvm/IR/DataLayout.h"
41
#include "llvm/IR/DerivedTypes.h"
42
#include "llvm/IR/Instructions.h"
43
#include "llvm/IR/Intrinsics.h"
44
#include "llvm/IR/Metadata.h"
45
#include "llvm/IR/Module.h"
46
#include "llvm/Support/FileSystem.h"
47
#include "llvm/Support/MD5.h"
48
#include "llvm/Support/Path.h"
49
#include "llvm/Support/TimeProfiler.h"
50
using namespace clang;
51
using namespace clang::CodeGen;
52
53
883k
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54
883k
  auto TI = Ctx.getTypeInfo(Ty);
55
883k
  return TI.AlignIsRequired ? 
TI.Align986
:
0882k
;
56
883k
}
57
58
301k
static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59
301k
  return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
60
301k
}
61
62
925k
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63
925k
  return D->hasAttr<AlignedAttr>() ? 
D->getMaxAlignment()1.10k
:
0924k
;
64
925k
}
65
66
CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
67
    : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
68
      DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
69
10.4k
      DBuilder(CGM.getModule()) {
70
10.4k
  for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
71
17
    DebugPrefixMap[KV.first] = KV.second;
72
10.4k
  CreateCompileUnit();
73
10.4k
}
74
75
10.4k
CGDebugInfo::~CGDebugInfo() {
76
10.4k
  assert(LexicalBlockStack.empty() &&
77
10.4k
         "Region stack mismatch, stack not empty!");
78
10.4k
}
79
80
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
81
                                       SourceLocation TemporaryLocation)
82
288k
    : CGF(&CGF) {
83
288k
  init(TemporaryLocation);
84
288k
}
85
86
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
87
                                       bool DefaultToEmpty,
88
                                       SourceLocation TemporaryLocation)
89
320k
    : CGF(&CGF) {
90
320k
  init(TemporaryLocation, DefaultToEmpty);
91
320k
}
92
93
void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
94
8.77M
                              bool DefaultToEmpty) {
95
8.77M
  auto *DI = CGF->getDebugInfo();
96
8.77M
  if (!DI) {
97
5.01M
    CGF = nullptr;
98
5.01M
    return;
99
5.01M
  }
100
101
3.76M
  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
102
103
3.76M
  if (OriginalLocation && 
!DI->CGM.getExpressionLocationsEnabled()3.75M
)
104
226
    return;
105
106
3.76M
  if (TemporaryLocation.isValid()) {
107
3.72M
    DI->EmitLocation(CGF->Builder, TemporaryLocation);
108
3.72M
    return;
109
3.72M
  }
110
111
39.7k
  if (DefaultToEmpty) {
112
27.9k
    CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
113
27.9k
    return;
114
27.9k
  }
115
116
  // Construct a location that has a valid scope, but no line info.
117
11.8k
  assert(!DI->LexicalBlockStack.empty());
118
0
  CGF->Builder.SetCurrentDebugLocation(
119
11.8k
      llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
120
11.8k
                            DI->LexicalBlockStack.back(), DI->getInlinedAt()));
121
11.8k
}
122
123
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
124
8.16M
    : CGF(&CGF) {
125
8.16M
  init(E->getExprLoc());
126
8.16M
}
127
128
ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
129
375k
    : CGF(&CGF) {
130
375k
  if (!CGF.getDebugInfo()) {
131
273k
    this->CGF = nullptr;
132
273k
    return;
133
273k
  }
134
102k
  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
135
102k
  if (Loc)
136
48.2k
    CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
137
102k
}
138
139
9.15M
ApplyDebugLocation::~ApplyDebugLocation() {
140
  // Query CGF so the location isn't overwritten when location updates are
141
  // temporarily disabled (for C++ default function arguments)
142
9.15M
  if (CGF)
143
3.86M
    CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
144
9.15M
}
145
146
ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
147
                                                   GlobalDecl InlinedFn)
148
47
    : CGF(&CGF) {
149
47
  if (!CGF.getDebugInfo()) {
150
44
    this->CGF = nullptr;
151
44
    return;
152
44
  }
153
3
  auto &DI = *CGF.getDebugInfo();
154
3
  SavedLocation = DI.getLocation();
155
3
  assert((DI.getInlinedAt() ==
156
3
          CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
157
3
         "CGDebugInfo and IRBuilder are out of sync");
158
159
0
  DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
160
3
}
161
162
47
ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
163
47
  if (!CGF)
164
44
    return;
165
3
  auto &DI = *CGF->getDebugInfo();
166
3
  DI.EmitInlineFunctionEnd(CGF->Builder);
167
3
  DI.EmitLocation(CGF->Builder, SavedLocation);
168
3
}
169
170
5.06M
void CGDebugInfo::setLocation(SourceLocation Loc) {
171
  // If the new location isn't valid return.
172
5.06M
  if (Loc.isInvalid())
173
3.67k
    return;
174
175
5.06M
  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
176
177
  // If we've changed files in the middle of a lexical scope go ahead
178
  // and create a new lexical scope with file node if it's different
179
  // from the one in the scope.
180
5.06M
  if (LexicalBlockStack.empty())
181
4.53k
    return;
182
183
5.06M
  SourceManager &SM = CGM.getContext().getSourceManager();
184
5.06M
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
185
5.06M
  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
186
5.06M
  if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
187
5.05M
    return;
188
189
186
  if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
190
4
    LexicalBlockStack.pop_back();
191
4
    LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
192
4
        LBF->getScope(), getOrCreateFile(CurLoc)));
193
182
  } else if (isa<llvm::DILexicalBlock>(Scope) ||
194
182
             isa<llvm::DISubprogram>(Scope)) {
195
182
    LexicalBlockStack.pop_back();
196
182
    LexicalBlockStack.emplace_back(
197
182
        DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
198
182
  }
199
186
}
200
201
784k
llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
202
784k
  llvm::DIScope *Mod = getParentModuleOrNull(D);
203
784k
  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
204
784k
                              Mod ? 
Mod410k
:
TheCU374k
);
205
784k
}
206
207
llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
208
1.04M
                                                 llvm::DIScope *Default) {
209
1.04M
  if (!Context)
210
0
    return Default;
211
212
1.04M
  auto I = RegionMap.find(Context);
213
1.04M
  if (I != RegionMap.end()) {
214
197k
    llvm::Metadata *V = I->second;
215
197k
    return dyn_cast_or_null<llvm::DIScope>(V);
216
197k
  }
217
218
  // Check namespace.
219
848k
  if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
220
236k
    return getOrCreateNamespace(NSDecl);
221
222
611k
  if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
223
12.1k
    if (!RDecl->isDependentType())
224
9.85k
      return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
225
9.85k
                             TheCU->getFile());
226
601k
  return Default;
227
611k
}
228
229
739k
PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
230
739k
  PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
231
232
  // If we're emitting codeview, it's important to try to match MSVC's naming so
233
  // that visualizers written for MSVC will trigger for our class names. In
234
  // particular, we can't have spaces between arguments of standard templates
235
  // like basic_string and vector, but we must have spaces between consecutive
236
  // angle brackets that close nested template argument lists.
237
739k
  if (CGM.getCodeGenOpts().EmitCodeView) {
238
359
    PP.MSVCFormatting = true;
239
359
    PP.SplitTemplateClosers = true;
240
739k
  } else {
241
    // For DWARF, printing rules are underspecified.
242
    // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
243
739k
    PP.SplitTemplateClosers = true;
244
739k
  }
245
246
  // Apply -fdebug-prefix-map.
247
739k
  PP.Callbacks = &PrintCB;
248
739k
  return PP;
249
739k
}
250
251
662k
StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
252
662k
  return internString(GetName(FD));
253
662k
}
254
255
13.5k
StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
256
13.5k
  SmallString<256> MethodName;
257
13.5k
  llvm::raw_svector_ostream OS(MethodName);
258
13.5k
  OS << (OMD->isInstanceMethod() ? 
'-'10.9k
:
'+'2.52k
) << '[';
259
13.5k
  const DeclContext *DC = OMD->getDeclContext();
260
13.5k
  if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
261
1.33k
    OS << OID->getName();
262
12.1k
  } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
263
8.28k
    OS << OID->getName();
264
8.28k
  } else 
if (const auto *3.88k
OC3.88k
= dyn_cast<ObjCCategoryDecl>(DC)) {
265
3.86k
    if (OC->IsClassExtension()) {
266
48
      OS << OC->getClassInterface()->getName();
267
3.81k
    } else {
268
3.81k
      OS << OC->getIdentifier()->getNameStart() << '('
269
3.81k
         << OC->getIdentifier()->getNameStart() << ')';
270
3.81k
    }
271
3.86k
  } else 
if (const auto *22
OCD22
= dyn_cast<ObjCCategoryImplDecl>(DC)) {
272
22
    OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
273
22
  }
274
13.5k
  OS << ' ' << OMD->getSelector().getAsString() << ']';
275
276
13.5k
  return internString(OS.str());
277
13.5k
}
278
279
618
StringRef CGDebugInfo::getSelectorName(Selector S) {
280
618
  return internString(S.getAsString());
281
618
}
282
283
149k
StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
284
149k
  if (isa<ClassTemplateSpecializationDecl>(RD)) {
285
    // Copy this name on the side and use its reference.
286
74.0k
    return internString(GetName(RD));
287
74.0k
  }
288
289
  // quick optimization to avoid having to intern strings that are already
290
  // stored reliably elsewhere
291
75.3k
  if (const IdentifierInfo *II = RD->getIdentifier())
292
57.7k
    return II->getName();
293
294
  // The CodeView printer in LLVM wants to see the names of unnamed types
295
  // because they need to have a unique identifier.
296
  // These names are used to reconstruct the fully qualified type names.
297
17.6k
  if (CGM.getCodeGenOpts().EmitCodeView) {
298
26
    if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
299
1
      assert(RD->getDeclContext() == D->getDeclContext() &&
300
1
             "Typedef should not be in another decl context!");
301
0
      assert(D->getDeclName().getAsIdentifierInfo() &&
302
1
             "Typedef was not named!");
303
0
      return D->getDeclName().getAsIdentifierInfo()->getName();
304
1
    }
305
306
25
    if (CGM.getLangOpts().CPlusPlus) {
307
24
      StringRef Name;
308
309
24
      ASTContext &Context = CGM.getContext();
310
24
      if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
311
        // Anonymous types without a name for linkage purposes have their
312
        // declarator mangled in if they have one.
313
6
        Name = DD->getName();
314
18
      else if (const TypedefNameDecl *TND =
315
18
                   Context.getTypedefNameForUnnamedTagDecl(RD))
316
        // Anonymous types without a name for linkage purposes have their
317
        // associate typedef mangled in if they have one.
318
1
        Name = TND->getName();
319
320
      // Give lambdas a display name based on their name mangling.
321
24
      if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
322
24
        if (CXXRD->isLambda())
323
16
          return internString(
324
16
              CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
325
326
8
      if (!Name.empty()) {
327
7
        SmallString<256> UnnamedType("<unnamed-type-");
328
7
        UnnamedType += Name;
329
7
        UnnamedType += '>';
330
7
        return internString(UnnamedType);
331
7
      }
332
8
    }
333
25
  }
334
335
17.5k
  return StringRef();
336
17.6k
}
337
338
Optional<llvm::DIFile::ChecksumKind>
339
84.8k
CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
340
84.8k
  Checksum.clear();
341
342
84.8k
  if (!CGM.getCodeGenOpts().EmitCodeView &&
343
84.8k
      
CGM.getCodeGenOpts().DwarfVersion < 584.8k
)
344
84.7k
    return None;
345
346
158
  SourceManager &SM = CGM.getContext().getSourceManager();
347
158
  Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
348
158
  if (!MemBuffer)
349
14
    return None;
350
351
144
  llvm::MD5 Hash;
352
144
  llvm::MD5::MD5Result Result;
353
354
144
  Hash.update(MemBuffer->getBuffer());
355
144
  Hash.final(Result);
356
357
144
  Hash.stringifyResult(Result, Checksum);
358
144
  return llvm::DIFile::CSK_MD5;
359
158
}
360
361
Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
362
85.2k
                                           FileID FID) {
363
85.2k
  if (!CGM.getCodeGenOpts().EmbedSource)
364
85.2k
    return None;
365
366
2
  bool SourceInvalid = false;
367
2
  StringRef Source = SM.getBufferData(FID, &SourceInvalid);
368
369
2
  if (SourceInvalid)
370
0
    return None;
371
372
2
  return Source;
373
2
}
374
375
7.38M
llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
376
7.38M
  SourceManager &SM = CGM.getContext().getSourceManager();
377
7.38M
  StringRef FileName;
378
7.38M
  FileID FID;
379
380
7.38M
  if (Loc.isInvalid()) {
381
    // The DIFile used by the CU is distinct from the main source file. Call
382
    // createFile() below for canonicalization if the source file was specified
383
    // with an absolute path.
384
8.54k
    FileName = TheCU->getFile()->getFilename();
385
7.37M
  } else {
386
7.37M
    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
387
7.37M
    FileName = PLoc.getFilename();
388
    
389
7.37M
    if (FileName.empty()) {
390
8
      FileName = TheCU->getFile()->getFilename();
391
7.37M
    } else {
392
7.37M
      FileName = PLoc.getFilename();
393
7.37M
    }
394
7.37M
    FID = PLoc.getFileID();
395
7.37M
  }
396
397
  // Cache the results.
398
7.38M
  auto It = DIFileCache.find(FileName.data());
399
7.38M
  if (It != DIFileCache.end()) {
400
    // Verify that the information still exists.
401
7.30M
    if (llvm::Metadata *V = It->second)
402
7.30M
      return cast<llvm::DIFile>(V);
403
7.30M
  }
404
405
74.7k
  SmallString<32> Checksum;
406
407
74.7k
  Optional<llvm::DIFile::ChecksumKind> CSKind = computeChecksum(FID, Checksum);
408
74.7k
  Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
409
74.7k
  if (CSKind)
410
73
    CSInfo.emplace(*CSKind, Checksum);
411
74.7k
  return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
412
7.38M
}
413
414
llvm::DIFile *
415
CGDebugInfo::createFile(StringRef FileName,
416
                        Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
417
74.7k
                        Optional<StringRef> Source) {
418
74.7k
  StringRef Dir;
419
74.7k
  StringRef File;
420
74.7k
  std::string RemappedFile = remapDIPath(FileName);
421
74.7k
  std::string CurDir = remapDIPath(getCurrentDirname());
422
74.7k
  SmallString<128> DirBuf;
423
74.7k
  SmallString<128> FileBuf;
424
74.7k
  if (llvm::sys::path::is_absolute(RemappedFile)) {
425
    // Strip the common prefix (if it is more than just "/") from current
426
    // directory and FileName for a more space-efficient encoding.
427
71.0k
    auto FileIt = llvm::sys::path::begin(RemappedFile);
428
71.0k
    auto FileE = llvm::sys::path::end(RemappedFile);
429
71.0k
    auto CurDirIt = llvm::sys::path::begin(CurDir);
430
71.0k
    auto CurDirE = llvm::sys::path::end(CurDir);
431
332k
    for (; CurDirIt != CurDirE && 
*CurDirIt == *FileIt332k
;
++CurDirIt, ++FileIt261k
)
432
261k
      llvm::sys::path::append(DirBuf, *CurDirIt);
433
71.0k
    if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
434
      // Don't strip the common prefix if it is only the root "/"
435
      // since that would make LLVM diagnostic locations confusing.
436
38.2k
      Dir = {};
437
38.2k
      File = RemappedFile;
438
38.2k
    } else {
439
248k
      for (; FileIt != FileE; 
++FileIt215k
)
440
215k
        llvm::sys::path::append(FileBuf, *FileIt);
441
32.8k
      Dir = DirBuf;
442
32.8k
      File = FileBuf;
443
32.8k
    }
444
71.0k
  } else {
445
3.71k
    Dir = CurDir;
446
3.71k
    File = RemappedFile;
447
3.71k
  }
448
74.7k
  llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
449
74.7k
  DIFileCache[FileName.data()].reset(F);
450
74.7k
  return F;
451
74.7k
}
452
453
213k
std::string CGDebugInfo::remapDIPath(StringRef Path) const {
454
213k
  if (DebugPrefixMap.empty())
455
213k
    return Path.str();
456
457
113
  SmallString<256> P = Path;
458
113
  for (const auto &Entry : DebugPrefixMap)
459
128
    if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
460
45
      break;
461
113
  return P.str().str();
462
213k
}
463
464
7.05M
unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
465
7.05M
  if (Loc.isInvalid())
466
8.37k
    return 0;
467
7.05M
  SourceManager &SM = CGM.getContext().getSourceManager();
468
7.05M
  return SM.getPresumedLoc(Loc).getLine();
469
7.05M
}
470
471
5.40M
unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
472
  // We may not want column information at all.
473
5.40M
  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
474
3.47M
    return 0;
475
476
  // If the location is invalid then use the current column.
477
1.92M
  if (Loc.isInvalid() && 
CurLoc.isInvalid()40
)
478
4
    return 0;
479
1.92M
  SourceManager &SM = CGM.getContext().getSourceManager();
480
1.92M
  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? 
Loc1.92M
:
CurLoc36
);
481
1.92M
  return PLoc.isValid() ? PLoc.getColumn() : 
00
;
482
1.92M
}
483
484
85.2k
StringRef CGDebugInfo::getCurrentDirname() {
485
85.2k
  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
486
45.3k
    return CGM.getCodeGenOpts().DebugCompilationDir;
487
488
39.9k
  if (!CWDName.empty())
489
32.8k
    return CWDName;
490
7.05k
  SmallString<256> CWD;
491
7.05k
  llvm::sys::fs::current_path(CWD);
492
7.05k
  return CWDName = internString(CWD);
493
39.9k
}
494
495
10.4k
void CGDebugInfo::CreateCompileUnit() {
496
10.4k
  SmallString<32> Checksum;
497
10.4k
  Optional<llvm::DIFile::ChecksumKind> CSKind;
498
10.4k
  Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
499
500
  // Should we be asking the SourceManager for the main file name, instead of
501
  // accepting it as an argument? This just causes the main file name to
502
  // mismatch with source locations and create extra lexical scopes or
503
  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
504
  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
505
  // because that's what the SourceManager says)
506
507
  // Get absolute path name.
508
10.4k
  SourceManager &SM = CGM.getContext().getSourceManager();
509
10.4k
  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
510
10.4k
  if (MainFileName.empty())
511
6.78k
    MainFileName = "<stdin>";
512
513
  // The main file name provided via the "-main-file-name" option contains just
514
  // the file name itself with no path information. This file name may have had
515
  // a relative path, so we look into the actual file entry for the main
516
  // file to determine the real absolute path for the file.
517
10.4k
  std::string MainFileDir;
518
10.4k
  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
519
10.0k
    MainFileDir = std::string(MainFile->getDir()->getName());
520
10.0k
    if (!llvm::sys::path::is_absolute(MainFileName)) {
521
10.0k
      llvm::SmallString<1024> MainFileDirSS(MainFileDir);
522
10.0k
      llvm::sys::path::append(MainFileDirSS, MainFileName);
523
10.0k
      MainFileName =
524
10.0k
          std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
525
10.0k
    }
526
    // If the main file name provided is identical to the input file name, and
527
    // if the input file is a preprocessed source, use the module name for
528
    // debug info. The module name comes from the name specified in the first
529
    // linemarker if the input is a preprocessed source.
530
10.0k
    if (MainFile->getName() == MainFileName &&
531
10.0k
        FrontendOptions::getInputKindForExtension(
532
3.40k
            MainFile->getName().rsplit('.').second)
533
3.40k
            .isPreprocessed())
534
1
      MainFileName = CGM.getModule().getName().str();
535
536
10.0k
    CSKind = computeChecksum(SM.getMainFileID(), Checksum);
537
10.0k
  }
538
539
10.4k
  llvm::dwarf::SourceLanguage LangTag;
540
10.4k
  const LangOptions &LO = CGM.getLangOpts();
541
10.4k
  if (LO.CPlusPlus) {
542
8.56k
    if (LO.ObjC)
543
6.10k
      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
544
2.46k
    else if (LO.CPlusPlus14 && 
(325
!CGM.getCodeGenOpts().DebugStrictDwarf325
||
545
325
                                
CGM.getCodeGenOpts().DwarfVersion >= 520
))
546
306
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
547
2.15k
    else if (LO.CPlusPlus11 && 
(2.13k
!CGM.getCodeGenOpts().DebugStrictDwarf2.13k
||
548
2.13k
                                
CGM.getCodeGenOpts().DwarfVersion >= 587
))
549
2.05k
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
550
108
    else
551
108
      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
552
8.56k
  } else 
if (1.89k
LO.ObjC1.89k
) {
553
561
    LangTag = llvm::dwarf::DW_LANG_ObjC;
554
1.33k
  } else if (LO.OpenCL && 
(18
!CGM.getCodeGenOpts().DebugStrictDwarf18
||
555
18
                           
CGM.getCodeGenOpts().DwarfVersion >= 52
)) {
556
17
    LangTag = llvm::dwarf::DW_LANG_OpenCL;
557
1.31k
  } else if (LO.RenderScript) {
558
1
    LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
559
1.31k
  } else if (LO.C99) {
560
1.31k
    LangTag = llvm::dwarf::DW_LANG_C99;
561
1.31k
  } else {
562
0
    LangTag = llvm::dwarf::DW_LANG_C89;
563
0
  }
564
565
10.4k
  std::string Producer = getClangFullVersion();
566
567
  // Figure out which version of the ObjC runtime we have.
568
10.4k
  unsigned RuntimeVers = 0;
569
10.4k
  if (LO.ObjC)
570
6.66k
    RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 
26.65k
:
16
;
571
572
10.4k
  llvm::DICompileUnit::DebugEmissionKind EmissionKind;
573
10.4k
  switch (DebugKind) {
574
15
  case codegenoptions::NoDebugInfo:
575
78
  case codegenoptions::LocTrackingOnly:
576
78
    EmissionKind = llvm::DICompileUnit::NoDebug;
577
78
    break;
578
71
  case codegenoptions::DebugLineTablesOnly:
579
71
    EmissionKind = llvm::DICompileUnit::LineTablesOnly;
580
71
    break;
581
19
  case codegenoptions::DebugDirectivesOnly:
582
19
    EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
583
19
    break;
584
106
  case codegenoptions::DebugInfoConstructor:
585
577
  case codegenoptions::LimitedDebugInfo:
586
10.2k
  case codegenoptions::FullDebugInfo:
587
10.2k
  case codegenoptions::UnusedTypeInfo:
588
10.2k
    EmissionKind = llvm::DICompileUnit::FullDebug;
589
10.2k
    break;
590
10.4k
  }
591
592
10.4k
  uint64_t DwoId = 0;
593
10.4k
  auto &CGOpts = CGM.getCodeGenOpts();
594
  // The DIFile used by the CU is distinct from the main source
595
  // file. Its directory part specifies what becomes the
596
  // DW_AT_comp_dir (the compilation directory), even if the source
597
  // file was specified with an absolute path.
598
10.4k
  if (CSKind)
599
71
    CSInfo.emplace(*CSKind, Checksum);
600
10.4k
  llvm::DIFile *CUFile = DBuilder.createFile(
601
10.4k
      remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
602
10.4k
      getSource(SM, SM.getMainFileID()));
603
604
10.4k
  StringRef Sysroot, SDK;
605
10.4k
  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
606
3.54k
    Sysroot = CGM.getHeaderSearchOpts().Sysroot;
607
3.54k
    auto B = llvm::sys::path::rbegin(Sysroot);
608
3.54k
    auto E = llvm::sys::path::rend(Sysroot);
609
3.57k
    auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
610
3.54k
    if (It != E)
611
3.46k
      SDK = *It;
612
3.54k
  }
613
614
  // Create new compile unit.
615
10.4k
  TheCU = DBuilder.createCompileUnit(
616
10.4k
      LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? 
Producer10.4k
:
""2
,
617
10.4k
      LO.Optimize || 
CGOpts.PrepareForLTO10.1k
||
CGOpts.PrepareForThinLTO10.1k
,
618
10.4k
      CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
619
10.4k
      DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
620
10.4k
      CGM.getTarget().getTriple().isNVPTX()
621
10.4k
          ? 
llvm::DICompileUnit::DebugNameTableKind::None12
622
10.4k
          : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
623
10.4k
                CGOpts.DebugNameTable),
624
10.4k
      CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
625
10.4k
}
626
627
175k
llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
628
175k
  llvm::dwarf::TypeKind Encoding;
629
175k
  StringRef BTName;
630
175k
  switch (BT->getKind()) {
631
0
#define BUILTIN_TYPE(Id, SingletonId)
632
0
#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
633
0
#include "clang/AST/BuiltinTypes.def"
634
0
  case BuiltinType::Dependent:
635
0
    llvm_unreachable("Unexpected builtin type");
636
577
  case BuiltinType::NullPtr:
637
577
    return DBuilder.createNullPtrType();
638
135k
  case BuiltinType::Void:
639
135k
    return nullptr;
640
2.73k
  case BuiltinType::ObjCClass:
641
2.73k
    if (!ClassTy)
642
2.57k
      ClassTy =
643
2.57k
          DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
644
2.57k
                                     "objc_class", TheCU, TheCU->getFile(), 0);
645
2.73k
    return ClassTy;
646
858
  case BuiltinType::ObjCId: {
647
    // typedef struct objc_class *Class;
648
    // typedef struct objc_object {
649
    //  Class isa;
650
    // } *id;
651
652
858
    if (ObjTy)
653
0
      return ObjTy;
654
655
858
    if (!ClassTy)
656
823
      ClassTy =
657
823
          DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
658
823
                                     "objc_class", TheCU, TheCU->getFile(), 0);
659
660
858
    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
661
662
858
    auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
663
664
858
    ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
665
858
                                      0, 0, llvm::DINode::FlagZero, nullptr,
666
858
                                      llvm::DINodeArray());
667
668
858
    DBuilder.replaceArrays(
669
858
        ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
670
858
                   ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
671
858
                   llvm::DINode::FlagZero, ISATy)));
672
858
    return ObjTy;
673
858
  }
674
341
  case BuiltinType::ObjCSel: {
675
341
    if (!SelTy)
676
341
      SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
677
341
                                         "objc_selector", TheCU,
678
341
                                         TheCU->getFile(), 0);
679
341
    return SelTy;
680
858
  }
681
682
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
683
0
  case BuiltinType::Id:                                                        \
684
0
    return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t",       \
685
0
                                    SingletonId);
686
341
#include "clang/Basic/OpenCLImageTypes.def"
687
0
  case BuiltinType::OCLSampler:
688
0
    return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
689
0
  case BuiltinType::OCLEvent:
690
0
    return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
691
0
  case BuiltinType::OCLClkEvent:
692
0
    return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
693
1
  case BuiltinType::OCLQueue:
694
1
    return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
695
0
  case BuiltinType::OCLReserveID:
696
0
    return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
697
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
698
0
  case BuiltinType::Id: \
699
0
    return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
700
0
#include "clang/Basic/OpenCLExtensionTypes.def"
701
702
1.14k
#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
703
45
#include 
"clang/Basic/AArch64SVEACLETypes.def"0
704
45
    {
705
45
      ASTContext::BuiltinVectorTypeInfo Info =
706
45
          CGM.getContext().getBuiltinVectorTypeInfo(BT);
707
45
      unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
708
709
      // Debuggers can't extract 1bit from a vector, so will display a
710
      // bitpattern for svbool_t instead.
711
45
      if (Info.ElementType == CGM.getContext().BoolTy) {
712
1
        NumElemsPerVG /= 8;
713
1
        Info.ElementType = CGM.getContext().UnsignedCharTy;
714
1
      }
715
716
45
      auto *LowerBound =
717
45
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
718
45
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
719
45
      SmallVector<int64_t, 9> Expr(
720
45
          {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
721
45
           /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
722
45
           llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
723
45
      auto *UpperBound = DBuilder.createExpression(Expr);
724
725
45
      llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
726
45
          /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
727
45
      llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
728
45
      llvm::DIType *ElemTy =
729
45
          getOrCreateType(Info.ElementType, TheCU->getFile());
730
45
      auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
731
45
      return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
732
45
                                       SubscriptArray);
733
1.10k
    }
734
  // It doesn't make sense to generate debug info for PowerPC MMA vector types.
735
  // So we return a safe type here to avoid generating an error.
736
0
#define PPC_VECTOR_TYPE(Name, Id, size) \
737
0
  case BuiltinType::Id:
738
45
#include "clang/Basic/PPCTypes.def"
739
0
    return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
740
741
140
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
742
3
#include 
"clang/Basic/RISCVVTypes.def"0
743
3
    {
744
3
      ASTContext::BuiltinVectorTypeInfo Info =
745
3
          CGM.getContext().getBuiltinVectorTypeInfo(BT);
746
747
3
      unsigned ElementCount = Info.EC.getKnownMinValue();
748
3
      unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
749
750
3
      bool Fractional = false;
751
3
      unsigned LMUL;
752
3
      unsigned FixedSize = ElementCount * SEW;
753
3
      if (Info.ElementType == CGM.getContext().BoolTy) {
754
        // Mask type only occupies one vector register.
755
0
        LMUL = 1;
756
3
      } else if (FixedSize < 64) {
757
        // In RVV scalable vector types, we encode 64 bits in the fixed part.
758
2
        Fractional = true;
759
2
        LMUL = 64 / FixedSize;
760
2
      } else {
761
1
        LMUL = FixedSize / 64;
762
1
      }
763
764
      // Element count = (VLENB / SEW) x LMUL
765
3
      SmallVector<int64_t, 9> Expr(
766
          // The DW_OP_bregx operation has two operands: a register which is
767
          // specified by an unsigned LEB128 number, followed by a signed LEB128
768
          // offset.
769
3
          {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
770
3
           4096 + 0xC22,             // RISC-V VLENB CSR register.
771
3
           0, // Offset for DW_OP_bregx. It is dummy here.
772
3
           llvm::dwarf::DW_OP_constu,
773
3
           SEW / 8, // SEW is in bits.
774
3
           llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
775
3
      if (Fractional)
776
2
        Expr.push_back(llvm::dwarf::DW_OP_div);
777
1
      else
778
1
        Expr.push_back(llvm::dwarf::DW_OP_mul);
779
780
3
      auto *LowerBound =
781
3
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
782
3
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
783
3
      auto *UpperBound = DBuilder.createExpression(Expr);
784
3
      llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
785
3
          /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
786
3
      llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
787
3
      llvm::DIType *ElemTy =
788
3
          getOrCreateType(Info.ElementType, TheCU->getFile());
789
790
3
      auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
791
3
      return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
792
3
                                       SubscriptArray);
793
137
    }
794
3.81k
  case BuiltinType::UChar:
795
3.82k
  case BuiltinType::Char_U:
796
3.82k
    Encoding = llvm::dwarf::DW_ATE_unsigned_char;
797
3.82k
    break;
798
4.70k
  case BuiltinType::Char_S:
799
5.92k
  case BuiltinType::SChar:
800
5.92k
    Encoding = llvm::dwarf::DW_ATE_signed_char;
801
5.92k
    break;
802
4
  case BuiltinType::Char8:
803
31
  case BuiltinType::Char16:
804
57
  case BuiltinType::Char32:
805
57
    Encoding = llvm::dwarf::DW_ATE_UTF;
806
57
    break;
807
694
  case BuiltinType::UShort:
808
6.67k
  case BuiltinType::UInt:
809
6.68k
  case BuiltinType::UInt128:
810
11.5k
  case BuiltinType::ULong:
811
11.5k
  case BuiltinType::WChar_U:
812
13.4k
  case BuiltinType::ULongLong:
813
13.4k
    Encoding = llvm::dwarf::DW_ATE_unsigned;
814
13.4k
    break;
815
834
  case BuiltinType::Short:
816
6.46k
  case BuiltinType::Int:
817
6.48k
  case BuiltinType::Int128:
818
7.51k
  case BuiltinType::Long:
819
8.10k
  case BuiltinType::WChar_S:
820
8.93k
  case BuiltinType::LongLong:
821
8.93k
    Encoding = llvm::dwarf::DW_ATE_signed;
822
8.93k
    break;
823
705
  case BuiltinType::Bool:
824
705
    Encoding = llvm::dwarf::DW_ATE_boolean;
825
705
    break;
826
7
  case BuiltinType::Half:
827
897
  case BuiltinType::Float:
828
1.57k
  case BuiltinType::LongDouble:
829
1.57k
  case BuiltinType::Float16:
830
1.57k
  case BuiltinType::BFloat16:
831
1.57k
  case BuiltinType::Float128:
832
2.46k
  case BuiltinType::Double:
833
    // FIXME: For targets where long double and __float128 have the same size,
834
    // they are currently indistinguishable in the debugger without some
835
    // special treatment. However, there is currently no consensus on encoding
836
    // and this should be updated once a DWARF encoding exists for distinct
837
    // floating point types of the same size.
838
2.46k
    Encoding = llvm::dwarf::DW_ATE_float;
839
2.46k
    break;
840
0
  case BuiltinType::ShortAccum:
841
0
  case BuiltinType::Accum:
842
0
  case BuiltinType::LongAccum:
843
0
  case BuiltinType::ShortFract:
844
0
  case BuiltinType::Fract:
845
0
  case BuiltinType::LongFract:
846
0
  case BuiltinType::SatShortFract:
847
0
  case BuiltinType::SatFract:
848
0
  case BuiltinType::SatLongFract:
849
0
  case BuiltinType::SatShortAccum:
850
0
  case BuiltinType::SatAccum:
851
0
  case BuiltinType::SatLongAccum:
852
0
    Encoding = llvm::dwarf::DW_ATE_signed_fixed;
853
0
    break;
854
0
  case BuiltinType::UShortAccum:
855
0
  case BuiltinType::UAccum:
856
0
  case BuiltinType::ULongAccum:
857
0
  case BuiltinType::UShortFract:
858
0
  case BuiltinType::UFract:
859
0
  case BuiltinType::ULongFract:
860
0
  case BuiltinType::SatUShortAccum:
861
0
  case BuiltinType::SatUAccum:
862
0
  case BuiltinType::SatULongAccum:
863
0
  case BuiltinType::SatUShortFract:
864
0
  case BuiltinType::SatUFract:
865
0
  case BuiltinType::SatULongFract:
866
0
    Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
867
0
    break;
868
175k
  }
869
870
35.3k
  switch (BT->getKind()) {
871
1.02k
  case BuiltinType::Long:
872
1.02k
    BTName = "long int";
873
1.02k
    break;
874
831
  case BuiltinType::LongLong:
875
831
    BTName = "long long int";
876
831
    break;
877
4.82k
  case BuiltinType::ULong:
878
4.82k
    BTName = "long unsigned int";
879
4.82k
    break;
880
1.97k
  case BuiltinType::ULongLong:
881
1.97k
    BTName = "long long unsigned int";
882
1.97k
    break;
883
26.7k
  default:
884
26.7k
    BTName = BT->getName(CGM.getLangOpts());
885
26.7k
    break;
886
35.3k
  }
887
  // Bit size and offset of the type.
888
35.3k
  uint64_t Size = CGM.getContext().getTypeSize(BT);
889
35.3k
  return DBuilder.createBasicType(BTName, Size, Encoding);
890
35.3k
}
891
892
12
llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
893
12
  return DBuilder.createUnspecifiedType("auto");
894
12
}
895
896
0
llvm::DIType *CGDebugInfo::CreateType(const ExtIntType *Ty) {
897
898
0
  StringRef Name = Ty->isUnsigned() ? "unsigned _ExtInt" : "_ExtInt";
899
0
  llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
900
0
                                       ? llvm::dwarf::DW_ATE_unsigned
901
0
                                       : llvm::dwarf::DW_ATE_signed;
902
903
0
  return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
904
0
                                  Encoding);
905
0
}
906
907
94
llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
908
  // Bit size and offset of the type.
909
94
  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
910
94
  if (Ty->isComplexIntegerType())
911
18
    Encoding = llvm::dwarf::DW_ATE_lo_user;
912
913
94
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
914
94
  return DBuilder.createBasicType("complex", Size, Encoding);
915
94
}
916
917
llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
918
73.1k
                                               llvm::DIFile *Unit) {
919
73.1k
  QualifierCollector Qc;
920
73.1k
  const Type *T = Qc.strip(Ty);
921
922
  // Ignore these qualifiers for now.
923
73.1k
  Qc.removeObjCGCAttr();
924
73.1k
  Qc.removeAddressSpace();
925
73.1k
  Qc.removeObjCLifetime();
926
927
  // We will create one Derived type for one qualifier and recurse to handle any
928
  // additional ones.
929
73.1k
  llvm::dwarf::Tag Tag;
930
73.1k
  if (Qc.hasConst()) {
931
70.5k
    Tag = llvm::dwarf::DW_TAG_const_type;
932
70.5k
    Qc.removeConst();
933
70.5k
  } else 
if (2.66k
Qc.hasVolatile()2.66k
) {
934
1.60k
    Tag = llvm::dwarf::DW_TAG_volatile_type;
935
1.60k
    Qc.removeVolatile();
936
1.60k
  } else 
if (1.05k
Qc.hasRestrict()1.05k
) {
937
879
    Tag = llvm::dwarf::DW_TAG_restrict_type;
938
879
    Qc.removeRestrict();
939
879
  } else {
940
176
    assert(Qc.empty() && "Unknown type qualifier for debug info");
941
0
    return getOrCreateType(QualType(T, 0), Unit);
942
176
  }
943
944
73.0k
  auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
945
946
  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
947
  // CVR derived types.
948
73.0k
  return DBuilder.createQualifiedType(Tag, FromTy);
949
73.1k
}
950
951
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
952
8.21k
                                      llvm::DIFile *Unit) {
953
954
  // The frontend treats 'id' as a typedef to an ObjCObjectType,
955
  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
956
  // debug info, we want to emit 'id' in both cases.
957
8.21k
  if (Ty->isObjCQualifiedIdType())
958
246
    return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
959
960
7.96k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
961
7.96k
                               Ty->getPointeeType(), Unit);
962
8.21k
}
963
964
llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
965
126k
                                      llvm::DIFile *Unit) {
966
126k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
967
126k
                               Ty->getPointeeType(), Unit);
968
126k
}
969
970
/// \return whether a C++ mangling exists for the type defined by TD.
971
164k
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
972
164k
  switch (TheCU->getSourceLanguage()) {
973
52.3k
  case llvm::dwarf::DW_LANG_C_plus_plus:
974
105k
  case llvm::dwarf::DW_LANG_C_plus_plus_11:
975
106k
  case llvm::dwarf::DW_LANG_C_plus_plus_14:
976
106k
    return true;
977
25.0k
  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
978
25.0k
    return isa<CXXRecordDecl>(TD) || 
isa<EnumDecl>(TD)4.82k
;
979
32.6k
  default:
980
32.6k
    return false;
981
164k
  }
982
164k
}
983
984
// Determines if the debug info for this tag declaration needs a type
985
// identifier. The purpose of the unique identifier is to deduplicate type
986
// information for identical types across TUs. Because of the C++ one definition
987
// rule (ODR), it is valid to assume that the type is defined the same way in
988
// every TU and its debug info is equivalent.
989
//
990
// C does not have the ODR, and it is common for codebases to contain multiple
991
// different definitions of a struct with the same name in different TUs.
992
// Therefore, if the type doesn't have a C++ mangling, don't give it an
993
// identifer. Type information in C is smaller and simpler than C++ type
994
// information, so the increase in debug info size is negligible.
995
//
996
// If the type is not externally visible, it should be unique to the current TU,
997
// and should not need an identifier to participate in type deduplication.
998
// However, when emitting CodeView, the format internally uses these
999
// unique type name identifers for references between debug info. For example,
1000
// the method of a class in an anonymous namespace uses the identifer to refer
1001
// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1002
// for such types, so when emitting CodeView, always use identifiers for C++
1003
// types. This may create problems when attempting to emit CodeView when the MS
1004
// C++ ABI is not in use.
1005
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1006
164k
                                llvm::DICompileUnit *TheCU) {
1007
  // We only add a type identifier for types with C++ name mangling.
1008
164k
  if (!hasCXXMangling(TD, TheCU))
1009
32.6k
    return false;
1010
1011
  // Externally visible types with C++ mangling need a type identifier.
1012
132k
  if (TD->isExternallyVisible())
1013
119k
    return true;
1014
1015
  // CodeView types with C++ mangling need a type identifier.
1016
12.2k
  if (CGM.getCodeGenOpts().EmitCodeView)
1017
19
    return true;
1018
1019
12.2k
  return false;
1020
12.2k
}
1021
1022
// Returns a unique type identifier string if one exists, or an empty string.
1023
static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1024
164k
                                          llvm::DICompileUnit *TheCU) {
1025
164k
  SmallString<256> Identifier;
1026
164k
  const TagDecl *TD = Ty->getDecl();
1027
1028
164k
  if (!needsTypeIdentifier(TD, CGM, TheCU))
1029
44.8k
    return Identifier;
1030
119k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1031
113k
    if (RD->getDefinition())
1032
102k
      if (RD->isDynamicClass() &&
1033
102k
          
CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage3.22k
)
1034
2.47k
        return Identifier;
1035
1036
  // TODO: This is using the RTTI name. Is there a better way to get
1037
  // a unique string for a type?
1038
117k
  llvm::raw_svector_ostream Out(Identifier);
1039
117k
  CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1040
117k
  return Identifier;
1041
119k
}
1042
1043
/// \return the appropriate DWARF tag for a composite type.
1044
136k
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1045
136k
  llvm::dwarf::Tag Tag;
1046
136k
  if (RD->isStruct() || 
RD->isInterface()30.0k
)
1047
106k
    Tag = llvm::dwarf::DW_TAG_structure_type;
1048
30.0k
  else if (RD->isUnion())
1049
2.96k
    Tag = llvm::dwarf::DW_TAG_union_type;
1050
27.0k
  else {
1051
    // FIXME: This could be a struct type giving a default visibility different
1052
    // than C++ class type, but needs llvm metadata changes first.
1053
27.0k
    assert(RD->isClass());
1054
0
    Tag = llvm::dwarf::DW_TAG_class_type;
1055
27.0k
  }
1056
0
  return Tag;
1057
136k
}
1058
1059
llvm::DICompositeType *
1060
CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1061
14.7k
                                      llvm::DIScope *Ctx) {
1062
14.7k
  const RecordDecl *RD = Ty->getDecl();
1063
14.7k
  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1064
4
    return cast<llvm::DICompositeType>(T);
1065
14.7k
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1066
14.7k
  const unsigned Line =
1067
14.7k
      getLineNumber(RD->getLocation().isValid() ? 
RD->getLocation()14.6k
:
CurLoc59
);
1068
14.7k
  StringRef RDName = getClassName(RD);
1069
1070
14.7k
  uint64_t Size = 0;
1071
14.7k
  uint32_t Align = 0;
1072
1073
14.7k
  const RecordDecl *D = RD->getDefinition();
1074
14.7k
  if (D && 
D->isCompleteDefinition()1.96k
)
1075
1.56k
    Size = CGM.getContext().getTypeSize(Ty);
1076
1077
14.7k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1078
1079
  // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1080
  // add the flag if a record has no definition because we don't know whether
1081
  // it will be trivial or not.
1082
14.7k
  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1083
12.5k
    if (!CXXRD->hasDefinition() ||
1084
12.5k
        
(1.67k
CXXRD->hasDefinition()1.67k
&&
!CXXRD->isTrivial()1.67k
))
1085
11.4k
      Flags |= llvm::DINode::FlagNonTrivial;
1086
1087
  // Create the type.
1088
14.7k
  SmallString<256> Identifier;
1089
  // Don't include a linkage name in line tables only.
1090
14.7k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1091
14.7k
    Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1092
14.7k
  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1093
14.7k
      getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1094
14.7k
      Identifier);
1095
14.7k
  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1096
1
    if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1097
1
      DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1098
1
                             CollectCXXTemplateParams(TSpecial, DefUnit));
1099
14.7k
  ReplaceMap.emplace_back(
1100
14.7k
      std::piecewise_construct, std::make_tuple(Ty),
1101
14.7k
      std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1102
14.7k
  return RetTy;
1103
14.7k
}
1104
1105
llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1106
                                                 const Type *Ty,
1107
                                                 QualType PointeeTy,
1108
239k
                                                 llvm::DIFile *Unit) {
1109
  // Bit size, align and offset of the type.
1110
  // Size is always the size of a pointer. We can't use getTypeSize here
1111
  // because that does not return the correct value for references.
1112
239k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1113
239k
  uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1114
239k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1115
239k
  Optional<unsigned> DWARFAddressSpace =
1116
239k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1117
1118
239k
  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1119
239k
      
Tag == llvm::dwarf::DW_TAG_rvalue_reference_type151k
)
1120
105k
    return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1121
105k
                                        Size, Align, DWARFAddressSpace);
1122
133k
  else
1123
133k
    return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1124
133k
                                      Align, DWARFAddressSpace);
1125
239k
}
1126
1127
llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1128
1
                                                    llvm::DIType *&Cache) {
1129
1
  if (Cache)
1130
0
    return Cache;
1131
1
  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1132
1
                                     TheCU, TheCU->getFile(), 0);
1133
1
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1134
1
  Cache = DBuilder.createPointerType(Cache, Size);
1135
1
  return Cache;
1136
1
}
1137
1138
uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1139
    const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1140
827
    unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1141
827
  QualType FType;
1142
1143
  // Advanced by calls to CreateMemberType in increments of FType, then
1144
  // returned as the overall size of the default elements.
1145
827
  uint64_t FieldOffset = 0;
1146
1147
  // Blocks in OpenCL have unique constraints which make the standard fields
1148
  // redundant while requiring size and align fields for enqueue_kernel. See
1149
  // initializeForBlockHeader in CGBlocks.cpp
1150
827
  if (CGM.getLangOpts().OpenCL) {
1151
4
    FType = CGM.getContext().IntTy;
1152
4
    EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1153
4
    EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1154
823
  } else {
1155
823
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1156
823
    EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1157
823
    FType = CGM.getContext().IntTy;
1158
823
    EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1159
823
    EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1160
823
    FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1161
823
    EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1162
823
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1163
823
    uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1164
823
    uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1165
823
    EltTys.push_back(DBuilder.createMemberType(
1166
823
        Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1167
823
        FieldOffset, llvm::DINode::FlagZero, DescTy));
1168
823
    FieldOffset += FieldSize;
1169
823
  }
1170
1171
827
  return FieldOffset;
1172
827
}
1173
1174
llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1175
827
                                      llvm::DIFile *Unit) {
1176
827
  SmallVector<llvm::Metadata *, 8> EltTys;
1177
827
  QualType FType;
1178
827
  uint64_t FieldOffset;
1179
827
  llvm::DINodeArray Elements;
1180
1181
827
  FieldOffset = 0;
1182
827
  FType = CGM.getContext().UnsignedLongTy;
1183
827
  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1184
827
  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1185
1186
827
  Elements = DBuilder.getOrCreateArray(EltTys);
1187
827
  EltTys.clear();
1188
1189
827
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1190
1191
827
  auto *EltTy =
1192
827
      DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1193
827
                                FieldOffset, 0, Flags, nullptr, Elements);
1194
1195
  // Bit size, align and offset of the type.
1196
827
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1197
1198
827
  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1199
1200
827
  FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1201
827
                                                          0, EltTys);
1202
1203
827
  Elements = DBuilder.getOrCreateArray(EltTys);
1204
1205
  // The __block_literal_generic structs are marked with a special
1206
  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1207
  // the debugger needs to know about. To allow type uniquing, emit
1208
  // them without a name or a location.
1209
827
  EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1210
827
                                    Flags, nullptr, Elements);
1211
1212
827
  return DBuilder.createPointerType(EltTy, Size);
1213
827
}
1214
1215
llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1216
7.08k
                                      llvm::DIFile *Unit) {
1217
7.08k
  assert(Ty->isTypeAlias());
1218
0
  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1219
1220
7.08k
  auto *AliasDecl =
1221
7.08k
      cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1222
7.08k
          ->getTemplatedDecl();
1223
1224
7.08k
  if (AliasDecl->hasAttr<NoDebugAttr>())
1225
5.79k
    return Src;
1226
1227
1.29k
  SmallString<128> NS;
1228
1.29k
  llvm::raw_svector_ostream OS(NS);
1229
1.29k
  Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1230
1.29k
  printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1231
1232
1.29k
  SourceLocation Loc = AliasDecl->getLocation();
1233
1.29k
  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1234
1.29k
                                getLineNumber(Loc),
1235
1.29k
                                getDeclContextDescriptor(AliasDecl));
1236
7.08k
}
1237
1238
llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1239
185k
                                      llvm::DIFile *Unit) {
1240
185k
  llvm::DIType *Underlying =
1241
185k
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1242
1243
185k
  if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1244
21.3k
    return Underlying;
1245
1246
  // We don't set size information, but do specify where the typedef was
1247
  // declared.
1248
164k
  SourceLocation Loc = Ty->getDecl()->getLocation();
1249
1250
164k
  uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1251
  // Typedefs are derived from some other type.
1252
164k
  return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1253
164k
                                getOrCreateFile(Loc), getLineNumber(Loc),
1254
164k
                                getDeclContextDescriptor(Ty->getDecl()), Align);
1255
185k
}
1256
1257
798k
static unsigned getDwarfCC(CallingConv CC) {
1258
798k
  switch (CC) {
1259
798k
  case CC_C:
1260
    // Avoid emitting DW_AT_calling_convention if the C convention was used.
1261
798k
    return 0;
1262
1263
2
  case CC_X86StdCall:
1264
2
    return llvm::dwarf::DW_CC_BORLAND_stdcall;
1265
2
  case CC_X86FastCall:
1266
2
    return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1267
117
  case CC_X86ThisCall:
1268
117
    return llvm::dwarf::DW_CC_BORLAND_thiscall;
1269
2
  case CC_X86VectorCall:
1270
2
    return llvm::dwarf::DW_CC_LLVM_vectorcall;
1271
1
  case CC_X86Pascal:
1272
1
    return llvm::dwarf::DW_CC_BORLAND_pascal;
1273
1
  case CC_Win64:
1274
1
    return llvm::dwarf::DW_CC_LLVM_Win64;
1275
1
  case CC_X86_64SysV:
1276
1
    return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1277
1
  case CC_AAPCS:
1278
1
  case CC_AArch64VectorCall:
1279
1
    return llvm::dwarf::DW_CC_LLVM_AAPCS;
1280
1
  case CC_AAPCS_VFP:
1281
1
    return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1282
1
  case CC_IntelOclBicc:
1283
1
    return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1284
2
  case CC_SpirFunction:
1285
2
    return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1286
11
  case CC_OpenCLKernel:
1287
11
    return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1288
1
  case CC_Swift:
1289
1
    return llvm::dwarf::DW_CC_LLVM_Swift;
1290
1
  case CC_SwiftAsync:
1291
    // [FIXME: swiftasynccc] Update to SwiftAsync once LLVM support lands.
1292
1
    return llvm::dwarf::DW_CC_LLVM_Swift;
1293
1
  case CC_PreserveMost:
1294
1
    return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1295
1
  case CC_PreserveAll:
1296
1
    return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1297
1
  case CC_X86RegCall:
1298
1
    return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1299
798k
  }
1300
0
  return 0;
1301
798k
}
1302
1303
llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1304
379k
                                      llvm::DIFile *Unit) {
1305
379k
  SmallVector<llvm::Metadata *, 16> EltTys;
1306
1307
  // Add the result type at least.
1308
379k
  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1309
1310
  // Set up remainder of arguments if there is a prototype.
1311
  // otherwise emit it as a variadic function.
1312
379k
  if (isa<FunctionNoProtoType>(Ty))
1313
22
    EltTys.push_back(DBuilder.createUnspecifiedParameter());
1314
379k
  else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1315
379k
    for (const QualType &ParamType : FPT->param_types())
1316
607k
      EltTys.push_back(getOrCreateType(ParamType, Unit));
1317
379k
    if (FPT->isVariadic())
1318
174
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
1319
379k
  }
1320
1321
379k
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1322
379k
  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1323
379k
                                       getDwarfCC(Ty->getCallConv()));
1324
379k
}
1325
1326
/// Convert an AccessSpecifier into the corresponding DINode flag.
1327
/// As an optimization, return 0 if the access specifier equals the
1328
/// default for the containing type.
1329
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1330
720k
                                           const RecordDecl *RD) {
1331
720k
  AccessSpecifier Default = clang::AS_none;
1332
720k
  if (RD && 
RD->isClass()718k
)
1333
352k
    Default = clang::AS_private;
1334
367k
  else if (RD && 
(365k
RD->isStruct()365k
||
RD->isUnion()16.9k
))
1335
365k
    Default = clang::AS_public;
1336
1337
720k
  if (Access == Default)
1338
414k
    return llvm::DINode::FlagZero;
1339
1340
305k
  switch (Access) {
1341
7.61k
  case clang::AS_private:
1342
7.61k
    return llvm::DINode::FlagPrivate;
1343
34.4k
  case clang::AS_protected:
1344
34.4k
    return llvm::DINode::FlagProtected;
1345
263k
  case clang::AS_public:
1346
263k
    return llvm::DINode::FlagPublic;
1347
109
  case clang::AS_none:
1348
109
    return llvm::DINode::FlagZero;
1349
305k
  }
1350
0
  llvm_unreachable("unexpected access enumerator");
1351
0
}
1352
1353
llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1354
                                              llvm::DIScope *RecordTy,
1355
6.66k
                                              const RecordDecl *RD) {
1356
6.66k
  StringRef Name = BitFieldDecl->getName();
1357
6.66k
  QualType Ty = BitFieldDecl->getType();
1358
6.66k
  SourceLocation Loc = BitFieldDecl->getLocation();
1359
6.66k
  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1360
6.66k
  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1361
1362
  // Get the location for the field.
1363
6.66k
  llvm::DIFile *File = getOrCreateFile(Loc);
1364
6.66k
  unsigned Line = getLineNumber(Loc);
1365
1366
6.66k
  const CGBitFieldInfo &BitFieldInfo =
1367
6.66k
      CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1368
6.66k
  uint64_t SizeInBits = BitFieldInfo.Size;
1369
6.66k
  assert(SizeInBits > 0 && "found named 0-width bitfield");
1370
0
  uint64_t StorageOffsetInBits =
1371
6.66k
      CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1372
6.66k
  uint64_t Offset = BitFieldInfo.Offset;
1373
  // The bit offsets for big endian machines are reversed for big
1374
  // endian target, compensate for that as the DIDerivedType requires
1375
  // un-reversed offsets.
1376
6.66k
  if (CGM.getDataLayout().isBigEndian())
1377
6
    Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1378
6.66k
  uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1379
6.66k
  llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1380
6.66k
  llvm::DINodeArray Annotations = CollectBTFTagAnnotations(BitFieldDecl);
1381
6.66k
  return DBuilder.createBitFieldMemberType(
1382
6.66k
      RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1383
6.66k
      Flags, DebugType, Annotations);
1384
6.66k
}
1385
1386
llvm::DIType *CGDebugInfo::createFieldType(
1387
    StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1388
    uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1389
292k
    llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1390
292k
  llvm::DIType *debugType = getOrCreateType(type, tunit);
1391
1392
  // Get the location for the field.
1393
292k
  llvm::DIFile *file = getOrCreateFile(loc);
1394
292k
  const unsigned line = getLineNumber(loc.isValid() ? 
loc290k
:
CurLoc2.68k
);
1395
1396
292k
  uint64_t SizeInBits = 0;
1397
292k
  auto Align = AlignInBits;
1398
292k
  if (!type->isIncompleteArrayType()) {
1399
292k
    TypeInfo TI = CGM.getContext().getTypeInfo(type);
1400
292k
    SizeInBits = TI.Width;
1401
292k
    if (!Align)
1402
292k
      Align = getTypeAlignIfRequired(type, CGM.getContext());
1403
292k
  }
1404
1405
292k
  llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1406
292k
  return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1407
292k
                                   offsetInBits, flags, debugType, Annotations);
1408
292k
}
1409
1410
void CGDebugInfo::CollectRecordLambdaFields(
1411
    const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1412
93
    llvm::DIType *RecordTy) {
1413
  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1414
  // has the name and the location of the variable so we should iterate over
1415
  // both concurrently.
1416
93
  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1417
93
  RecordDecl::field_iterator Field = CXXDecl->field_begin();
1418
93
  unsigned fieldno = 0;
1419
93
  for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1420
93
                                             E = CXXDecl->captures_end();
1421
154
       I != E; 
++I, ++Field, ++fieldno61
) {
1422
61
    const LambdaCapture &C = *I;
1423
61
    if (C.capturesVariable()) {
1424
54
      SourceLocation Loc = C.getLocation();
1425
54
      assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1426
0
      VarDecl *V = C.getCapturedVar();
1427
54
      StringRef VName = V->getName();
1428
54
      llvm::DIFile *VUnit = getOrCreateFile(Loc);
1429
54
      auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1430
54
      llvm::DIType *FieldType = createFieldType(
1431
54
          VName, Field->getType(), Loc, Field->getAccess(),
1432
54
          layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1433
54
      elements.push_back(FieldType);
1434
54
    } else 
if (7
C.capturesThis()7
) {
1435
      // TODO: Need to handle 'this' in some way by probably renaming the
1436
      // this of the lambda class and having a field member of 'this' or
1437
      // by using AT_object_pointer for the function and having that be
1438
      // used as 'this' for semantic references.
1439
7
      FieldDecl *f = *Field;
1440
7
      llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1441
7
      QualType type = f->getType();
1442
7
      llvm::DIType *fieldType = createFieldType(
1443
7
          "this", type, f->getLocation(), f->getAccess(),
1444
7
          layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1445
1446
7
      elements.push_back(fieldType);
1447
7
    }
1448
61
  }
1449
93
}
1450
1451
llvm::DIDerivedType *
1452
CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1453
34.0k
                                     const RecordDecl *RD) {
1454
  // Create the descriptor for the static variable, with or without
1455
  // constant initializers.
1456
34.0k
  Var = Var->getCanonicalDecl();
1457
34.0k
  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1458
34.0k
  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1459
1460
34.0k
  unsigned LineNumber = getLineNumber(Var->getLocation());
1461
34.0k
  StringRef VName = Var->getName();
1462
34.0k
  llvm::Constant *C = nullptr;
1463
34.0k
  if (Var->getInit()) {
1464
32.1k
    const APValue *Value = Var->evaluateValue();
1465
32.1k
    if (Value) {
1466
32.1k
      if (Value->isInt())
1467
32.1k
        C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1468
32.1k
      if (Value->isFloat())
1469
4
        C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1470
32.1k
    }
1471
32.1k
  }
1472
1473
34.0k
  llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1474
34.0k
  auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1475
34.0k
  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1476
34.0k
      RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1477
34.0k
  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1478
34.0k
  return GV;
1479
34.0k
}
1480
1481
void CGDebugInfo::CollectRecordNormalField(
1482
    const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1483
    SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1484
297k
    const RecordDecl *RD) {
1485
297k
  StringRef name = field->getName();
1486
297k
  QualType type = field->getType();
1487
1488
  // Ignore unnamed fields unless they're anonymous structs/unions.
1489
297k
  if (name.empty() && 
!type->isRecordType()892
)
1490
148
    return;
1491
1492
297k
  llvm::DIType *FieldType;
1493
297k
  if (field->isBitField()) {
1494
6.66k
    FieldType = createBitFieldType(field, RecordTy, RD);
1495
290k
  } else {
1496
290k
    auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1497
290k
    llvm::DINodeArray Annotations = CollectBTFTagAnnotations(field);
1498
290k
    FieldType =
1499
290k
        createFieldType(name, type, field->getLocation(), field->getAccess(),
1500
290k
                        OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1501
290k
  }
1502
1503
297k
  elements.push_back(FieldType);
1504
297k
}
1505
1506
void CGDebugInfo::CollectRecordNestedType(
1507
12
    const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1508
12
  QualType Ty = CGM.getContext().getTypeDeclType(TD);
1509
  // Injected class names are not considered nested records.
1510
12
  if (isa<InjectedClassNameType>(Ty))
1511
1
    return;
1512
11
  SourceLocation Loc = TD->getLocation();
1513
11
  llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1514
11
  elements.push_back(nestedType);
1515
11
}
1516
1517
void CGDebugInfo::CollectRecordFields(
1518
    const RecordDecl *record, llvm::DIFile *tunit,
1519
    SmallVectorImpl<llvm::Metadata *> &elements,
1520
121k
    llvm::DICompositeType *RecordTy) {
1521
121k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1522
1523
121k
  if (CXXDecl && 
CXXDecl->isLambda()105k
)
1524
93
    CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1525
121k
  else {
1526
121k
    const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1527
1528
    // Field number for non-static fields.
1529
121k
    unsigned fieldNo = 0;
1530
1531
    // Static and non-static members should appear in the same order as
1532
    // the corresponding declarations in the source program.
1533
121k
    for (const auto *I : record->decls())
1534
1.19M
      if (const auto *V = dyn_cast<VarDecl>(I)) {
1535
33.9k
        if (V->hasAttr<NoDebugAttr>())
1536
2
          continue;
1537
1538
        // Skip variable template specializations when emitting CodeView. MSVC
1539
        // doesn't emit them.
1540
33.9k
        if (CGM.getCodeGenOpts().EmitCodeView &&
1541
33.9k
            
isa<VarTemplateSpecializationDecl>(V)15
)
1542
5
          continue;
1543
1544
33.9k
        if (isa<VarTemplatePartialSpecializationDecl>(V))
1545
1
          continue;
1546
1547
        // Reuse the existing static member declaration if one exists
1548
33.9k
        auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1549
33.9k
        if (MI != StaticDataMemberCache.end()) {
1550
0
          assert(MI->second &&
1551
0
                 "Static data member declaration should still exist");
1552
0
          elements.push_back(MI->second);
1553
33.9k
        } else {
1554
33.9k
          auto Field = CreateRecordStaticField(V, RecordTy, record);
1555
33.9k
          elements.push_back(Field);
1556
33.9k
        }
1557
1.16M
      } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1558
297k
        CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1559
297k
                                 elements, RecordTy, record);
1560
1561
        // Bump field number for next field.
1562
297k
        ++fieldNo;
1563
864k
      } else if (CGM.getCodeGenOpts().EmitCodeView) {
1564
        // Debug info for nested types is included in the member list only for
1565
        // CodeView.
1566
399
        if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1567
93
          if (!nestedType->isImplicit() &&
1568
93
              
nestedType->getDeclContext() == record12
)
1569
12
            CollectRecordNestedType(nestedType, elements);
1570
399
      }
1571
121k
  }
1572
121k
}
1573
1574
llvm::DISubroutineType *
1575
CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1576
431k
                                   llvm::DIFile *Unit, bool decl) {
1577
431k
  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1578
431k
  if (Method->isStatic())
1579
33.1k
    return cast_or_null<llvm::DISubroutineType>(
1580
33.1k
        getOrCreateType(QualType(Func, 0), Unit));
1581
398k
  return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1582
431k
}
1583
1584
llvm::DISubroutineType *
1585
CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1586
                                           const FunctionProtoType *Func,
1587
398k
                                           llvm::DIFile *Unit, bool decl) {
1588
  // Add "this" pointer.
1589
398k
  llvm::DITypeRefArray Args(
1590
398k
      cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1591
398k
          ->getTypeArray());
1592
398k
  assert(Args.size() && "Invalid number of arguments!");
1593
1594
0
  SmallVector<llvm::Metadata *, 16> Elts;
1595
  // First element is always return type. For 'void' functions it is NULL.
1596
398k
  QualType temp = Func->getReturnType();
1597
398k
  if (temp->getTypeClass() == Type::Auto && 
decl28
)
1598
12
    Elts.push_back(CreateType(cast<AutoType>(temp)));
1599
398k
  else
1600
398k
    Elts.push_back(Args[0]);
1601
1602
  // "this" pointer is always first argument.
1603
398k
  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1604
398k
  if (isa<ClassTemplateSpecializationDecl>(RD)) {
1605
    // Create pointer type directly in this case.
1606
326k
    const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1607
326k
    QualType PointeeTy = ThisPtrTy->getPointeeType();
1608
326k
    unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1609
326k
    uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1610
326k
    auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1611
326k
    llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1612
326k
    llvm::DIType *ThisPtrType =
1613
326k
        DBuilder.createPointerType(PointeeType, Size, Align);
1614
326k
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1615
    // TODO: This and the artificial type below are misleading, the
1616
    // types aren't artificial the argument is, but the current
1617
    // metadata doesn't represent that.
1618
326k
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1619
326k
    Elts.push_back(ThisPtrType);
1620
326k
  } else {
1621
71.4k
    llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1622
71.4k
    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1623
71.4k
    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1624
71.4k
    Elts.push_back(ThisPtrType);
1625
71.4k
  }
1626
1627
  // Copy rest of the arguments.
1628
749k
  for (unsigned i = 1, e = Args.size(); i != e; 
++i351k
)
1629
351k
    Elts.push_back(Args[i]);
1630
1631
398k
  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1632
1633
398k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1634
398k
  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1635
73
    Flags |= llvm::DINode::FlagLValueReference;
1636
398k
  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1637
58
    Flags |= llvm::DINode::FlagRValueReference;
1638
1639
398k
  return DBuilder.createSubroutineType(EltTypeArray, Flags,
1640
398k
                                       getDwarfCC(Func->getCallConv()));
1641
398k
}
1642
1643
/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1644
/// inside a function.
1645
286k
static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1646
286k
  if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1647
1.23k
    return isFunctionLocalClass(NRD);
1648
285k
  if (isa<FunctionDecl>(RD->getDeclContext()))
1649
129
    return true;
1650
284k
  return false;
1651
285k
}
1652
1653
llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1654
362k
    const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1655
362k
  bool IsCtorOrDtor =
1656
362k
      isa<CXXConstructorDecl>(Method) || 
isa<CXXDestructorDecl>(Method)295k
;
1657
1658
362k
  StringRef MethodName = getFunctionName(Method);
1659
362k
  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1660
1661
  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1662
  // make sense to give a single ctor/dtor a linkage name.
1663
362k
  StringRef MethodLinkageName;
1664
  // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1665
  // property to use here. It may've been intended to model "is non-external
1666
  // type" but misses cases of non-function-local but non-external classes such
1667
  // as those in anonymous namespaces as well as the reverse - external types
1668
  // that are function local, such as those in (non-local) inline functions.
1669
362k
  if (!IsCtorOrDtor && 
!isFunctionLocalClass(Method->getParent())285k
)
1670
284k
    MethodLinkageName = CGM.getMangledName(Method);
1671
1672
  // Get the location for the method.
1673
362k
  llvm::DIFile *MethodDefUnit = nullptr;
1674
362k
  unsigned MethodLine = 0;
1675
362k
  if (!Method->isImplicit()) {
1676
360k
    MethodDefUnit = getOrCreateFile(Method->getLocation());
1677
360k
    MethodLine = getLineNumber(Method->getLocation());
1678
360k
  }
1679
1680
  // Collect virtual method info.
1681
362k
  llvm::DIType *ContainingType = nullptr;
1682
362k
  unsigned VIndex = 0;
1683
362k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1684
362k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1685
362k
  int ThisAdjustment = 0;
1686
1687
362k
  if (Method->isVirtual()) {
1688
9.11k
    if (Method->isPure())
1689
390
      SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1690
8.72k
    else
1691
8.72k
      SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1692
1693
9.11k
    if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1694
      // It doesn't make sense to give a virtual destructor a vtable index,
1695
      // since a single destructor has two entries in the vtable.
1696
9.07k
      if (!isa<CXXDestructorDecl>(Method))
1697
6.67k
        VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1698
9.07k
    } else {
1699
      // Emit MS ABI vftable information.  There is only one entry for the
1700
      // deleting dtor.
1701
33
      const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1702
33
      GlobalDecl GD = DD ? 
GlobalDecl(DD, Dtor_Deleting)2
:
GlobalDecl(Method)31
;
1703
33
      MethodVFTableLocation ML =
1704
33
          CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1705
33
      VIndex = ML.Index;
1706
1707
      // CodeView only records the vftable offset in the class that introduces
1708
      // the virtual method. This is possible because, unlike Itanium, the MS
1709
      // C++ ABI does not include all virtual methods from non-primary bases in
1710
      // the vtable for the most derived class. For example, if C inherits from
1711
      // A and B, C's primary vftable will not include B's virtual methods.
1712
33
      if (Method->size_overridden_methods() == 0)
1713
20
        Flags |= llvm::DINode::FlagIntroducedVirtual;
1714
1715
      // The 'this' adjustment accounts for both the virtual and non-virtual
1716
      // portions of the adjustment. Presumably the debugger only uses it when
1717
      // it knows the dynamic type of an object.
1718
33
      ThisAdjustment = CGM.getCXXABI()
1719
33
                           .getVirtualFunctionPrologueThisAdjustment(GD)
1720
33
                           .getQuantity();
1721
33
    }
1722
9.11k
    ContainingType = RecordTy;
1723
9.11k
  }
1724
1725
  // We're checking for deleted C++ special member functions
1726
  // [Ctors,Dtors, Copy/Move]
1727
362k
  auto checkAttrDeleted = [&](const auto *Method) {
1728
88.7k
    if (Method->getCanonicalDecl()->isDeleted())
1729
4.34k
      SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1730
88.7k
  };
1731
1732
362k
  switch (Method->getKind()) {
1733
1734
66.8k
  case Decl::CXXConstructor:
1735
77.0k
  case Decl::CXXDestructor:
1736
77.0k
    checkAttrDeleted(Method);
1737
77.0k
    break;
1738
280k
  case Decl::CXXMethod:
1739
280k
    if (Method->isCopyAssignmentOperator() ||
1740
280k
        
Method->isMoveAssignmentOperator()272k
)
1741
11.6k
      checkAttrDeleted(Method);
1742
280k
    break;
1743
4.70k
  default:
1744
4.70k
    break;
1745
362k
  }
1746
1747
362k
  if (Method->isNoReturn())
1748
1.88k
    Flags |= llvm::DINode::FlagNoReturn;
1749
1750
362k
  if (Method->isStatic())
1751
28.1k
    Flags |= llvm::DINode::FlagStaticMember;
1752
362k
  if (Method->isImplicit())
1753
1.54k
    Flags |= llvm::DINode::FlagArtificial;
1754
362k
  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1755
362k
  if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1756
66.8k
    if (CXXC->isExplicit())
1757
11.7k
      Flags |= llvm::DINode::FlagExplicit;
1758
295k
  } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1759
4.70k
    if (CXXC->isExplicit())
1760
3.10k
      Flags |= llvm::DINode::FlagExplicit;
1761
4.70k
  }
1762
362k
  if (Method->hasPrototype())
1763
362k
    Flags |= llvm::DINode::FlagPrototyped;
1764
362k
  if (Method->getRefQualifier() == RQ_LValue)
1765
56
    Flags |= llvm::DINode::FlagLValueReference;
1766
362k
  if (Method->getRefQualifier() == RQ_RValue)
1767
56
    Flags |= llvm::DINode::FlagRValueReference;
1768
362k
  if (!Method->isExternallyVisible())
1769
4.40k
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
1770
362k
  if (CGM.getLangOpts().Optimize)
1771
865
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1772
1773
  // In this debug mode, emit type info for a class when its constructor type
1774
  // info is emitted.
1775
362k
  if (DebugKind == codegenoptions::DebugInfoConstructor)
1776
154
    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1777
76
      completeUnusedClass(*CD->getParent());
1778
1779
362k
  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1780
362k
  llvm::DISubprogram *SP = DBuilder.createMethod(
1781
362k
      RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1782
362k
      MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1783
362k
      TParamsArray.get());
1784
1785
362k
  SPCache[Method->getCanonicalDecl()].reset(SP);
1786
1787
362k
  return SP;
1788
362k
}
1789
1790
void CGDebugInfo::CollectCXXMemberFunctions(
1791
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
1792
105k
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1793
1794
  // Since we want more than just the individual member decls if we
1795
  // have templated functions iterate over every declaration to gather
1796
  // the functions.
1797
1.10M
  for (const auto *I : RD->decls()) {
1798
1.10M
    const auto *Method = dyn_cast<CXXMethodDecl>(I);
1799
    // If the member is implicit, don't add it to the member list. This avoids
1800
    // the member being added to type units by LLVM, while still allowing it
1801
    // to be emitted into the type declaration/reference inside the compile
1802
    // unit.
1803
    // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1804
    // FIXME: Handle Using(Shadow?)Decls here to create
1805
    // DW_TAG_imported_declarations inside the class for base decls brought into
1806
    // derived classes. GDB doesn't seem to notice/leverage these when I tried
1807
    // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1808
    // referenced)
1809
1.10M
    if (!Method || 
Method->isImplicit()433k
||
Method->hasAttr<NoDebugAttr>()349k
)
1810
757k
      continue;
1811
1812
349k
    if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1813
39
      continue;
1814
1815
    // Reuse the existing member function declaration if it exists.
1816
    // It may be associated with the declaration of the type & should be
1817
    // reused as we're building the definition.
1818
    //
1819
    // This situation can arise in the vtable-based debug info reduction where
1820
    // implicit members are emitted in a non-vtable TU.
1821
349k
    auto MI = SPCache.find(Method->getCanonicalDecl());
1822
349k
    EltTys.push_back(MI == SPCache.end()
1823
349k
                         ? 
CreateCXXMemberFunction(Method, Unit, RecordTy)349k
1824
349k
                         : 
static_cast<llvm::Metadata *>(MI->second)76
);
1825
349k
  }
1826
105k
}
1827
1828
void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1829
                                  SmallVectorImpl<llvm::Metadata *> &EltTys,
1830
105k
                                  llvm::DIType *RecordTy) {
1831
105k
  llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1832
105k
  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1833
105k
                     llvm::DINode::FlagZero);
1834
1835
  // If we are generating CodeView debug info, we also need to emit records for
1836
  // indirect virtual base classes.
1837
105k
  if (CGM.getCodeGenOpts().EmitCodeView) {
1838
94
    CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1839
94
                       llvm::DINode::FlagIndirectVirtualBase);
1840
94
  }
1841
105k
}
1842
1843
void CGDebugInfo::CollectCXXBasesAux(
1844
    const CXXRecordDecl *RD, llvm::DIFile *Unit,
1845
    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1846
    const CXXRecordDecl::base_class_const_range &Bases,
1847
    llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1848
105k
    llvm::DINode::DIFlags StartingFlags) {
1849
105k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1850
105k
  for (const auto &BI : Bases) {
1851
24.9k
    const auto *Base =
1852
24.9k
        cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1853
24.9k
    if (!SeenTypes.insert(Base).second)
1854
3
      continue;
1855
24.9k
    auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1856
24.9k
    llvm::DINode::DIFlags BFlags = StartingFlags;
1857
24.9k
    uint64_t BaseOffset;
1858
24.9k
    uint32_t VBPtrOffset = 0;
1859
1860
24.9k
    if (BI.isVirtual()) {
1861
111
      if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1862
        // virtual base offset offset is -ve. The code generator emits dwarf
1863
        // expression where it expects +ve number.
1864
106
        BaseOffset = 0 - CGM.getItaniumVTableContext()
1865
106
                             .getVirtualBaseOffsetOffset(RD, Base)
1866
106
                             .getQuantity();
1867
106
      } else {
1868
        // In the MS ABI, store the vbtable offset, which is analogous to the
1869
        // vbase offset offset in Itanium.
1870
5
        BaseOffset =
1871
5
            4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1872
5
        VBPtrOffset = CGM.getContext()
1873
5
                          .getASTRecordLayout(RD)
1874
5
                          .getVBPtrOffset()
1875
5
                          .getQuantity();
1876
5
      }
1877
111
      BFlags |= llvm::DINode::FlagVirtual;
1878
111
    } else
1879
24.8k
      BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1880
    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1881
    // BI->isVirtual() and bits when not.
1882
1883
24.9k
    BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1884
24.9k
    llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1885
24.9k
                                                   VBPtrOffset, BFlags);
1886
24.9k
    EltTys.push_back(DTy);
1887
24.9k
  }
1888
105k
}
1889
1890
llvm::DINodeArray
1891
CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1892
                                   ArrayRef<TemplateArgument> TAList,
1893
118k
                                   llvm::DIFile *Unit) {
1894
118k
  SmallVector<llvm::Metadata *, 16> TemplateParams;
1895
318k
  for (unsigned i = 0, e = TAList.size(); i != e; 
++i199k
) {
1896
199k
    const TemplateArgument &TA = TAList[i];
1897
199k
    StringRef Name;
1898
199k
    bool defaultParameter = false;
1899
199k
    if (TPList)
1900
178k
      Name = TPList->getParam(i)->getName();
1901
199k
    switch (TA.getKind()) {
1902
147k
    case TemplateArgument::Type: {
1903
147k
      llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1904
1905
147k
      if (TPList)
1906
129k
        if (auto *templateType =
1907
129k
                dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1908
129k
          if (templateType->hasDefaultArgument())
1909
20.9k
            defaultParameter =
1910
20.9k
                templateType->getDefaultArgument() == TA.getAsType();
1911
1912
147k
      TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1913
147k
          TheCU, Name, TTy, defaultParameter));
1914
1915
147k
    } break;
1916
34.7k
    case TemplateArgument::Integral: {
1917
34.7k
      llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1918
34.7k
      if (TPList && 
CGM.getCodeGenOpts().DwarfVersion >= 531.6k
)
1919
6
        if (auto *templateType =
1920
6
                dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
1921
6
          if (templateType->hasDefaultArgument() &&
1922
6
              !templateType->getDefaultArgument()->isValueDependent())
1923
4
            defaultParameter = llvm::APSInt::isSameValue(
1924
4
                templateType->getDefaultArgument()->EvaluateKnownConstInt(
1925
4
                    CGM.getContext()),
1926
4
                TA.getAsIntegral());
1927
1928
34.7k
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1929
34.7k
          TheCU, Name, TTy, defaultParameter,
1930
34.7k
          llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1931
34.7k
    } break;
1932
22
    case TemplateArgument::Declaration: {
1933
22
      const ValueDecl *D = TA.getAsDecl();
1934
22
      QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1935
22
      llvm::DIType *TTy = getOrCreateType(T, Unit);
1936
22
      llvm::Constant *V = nullptr;
1937
      // Skip retrieve the value if that template parameter has cuda device
1938
      // attribute, i.e. that value is not available at the host side.
1939
22
      if (!CGM.getLangOpts().CUDA || 
CGM.getLangOpts().CUDAIsDevice1
||
1940
22
          
!D->hasAttr<CUDADeviceAttr>()1
) {
1941
21
        const CXXMethodDecl *MD;
1942
        // Variable pointer template parameters have a value that is the address
1943
        // of the variable.
1944
21
        if (const auto *VD = dyn_cast<VarDecl>(D))
1945
4
          V = CGM.GetAddrOfGlobalVar(VD);
1946
        // Member function pointers have special support for building them,
1947
        // though this is currently unsupported in LLVM CodeGen.
1948
17
        else if ((MD = dyn_cast<CXXMethodDecl>(D)) && 
MD->isInstance()2
)
1949
1
          V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1950
16
        else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1951
8
          V = CGM.GetAddrOfFunction(FD);
1952
        // Member data pointers have special handling too to compute the fixed
1953
        // offset within the object.
1954
8
        else if (const auto *MPT =
1955
8
                     dyn_cast<MemberPointerType>(T.getTypePtr())) {
1956
          // These five lines (& possibly the above member function pointer
1957
          // handling) might be able to be refactored to use similar code in
1958
          // CodeGenModule::getMemberPointerConstant
1959
2
          uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1960
2
          CharUnits chars =
1961
2
              CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1962
2
          V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1963
6
        } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
1964
4
          V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
1965
4
        } else 
if (const auto *2
TPO2
= dyn_cast<TemplateParamObjectDecl>(D)) {
1966
2
          if (T->isRecordType())
1967
1
            V = ConstantEmitter(CGM).emitAbstract(
1968
1
                SourceLocation(), TPO->getValue(), TPO->getType());
1969
1
          else
1970
1
            V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
1971
2
        }
1972
21
        assert(V && "Failed to find template parameter pointer");
1973
0
        V = V->stripPointerCasts();
1974
21
      }
1975
0
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1976
22
          TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
1977
22
    } break;
1978
4
    case TemplateArgument::NullPtr: {
1979
4
      QualType T = TA.getNullPtrType();
1980
4
      llvm::DIType *TTy = getOrCreateType(T, Unit);
1981
4
      llvm::Constant *V = nullptr;
1982
      // Special case member data pointer null values since they're actually -1
1983
      // instead of zero.
1984
4
      if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1985
        // But treat member function pointers as simple zero integers because
1986
        // it's easier than having a special case in LLVM's CodeGen. If LLVM
1987
        // CodeGen grows handling for values of non-null member function
1988
        // pointers then perhaps we could remove this special case and rely on
1989
        // EmitNullMemberPointer for member function pointers.
1990
2
        if (MPT->isMemberDataPointer())
1991
1
          V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1992
4
      if (!V)
1993
3
        V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1994
4
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1995
4
          TheCU, Name, TTy, defaultParameter, V));
1996
4
    } break;
1997
341
    case TemplateArgument::Template:
1998
341
      TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1999
341
          TheCU, Name, nullptr,
2000
341
          TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
2001
341
      break;
2002
17.3k
    case TemplateArgument::Pack:
2003
17.3k
      TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2004
17.3k
          TheCU, Name, nullptr,
2005
17.3k
          CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
2006
17.3k
      break;
2007
0
    case TemplateArgument::Expression: {
2008
0
      const Expr *E = TA.getAsExpr();
2009
0
      QualType T = E->getType();
2010
0
      if (E->isGLValue())
2011
0
        T = CGM.getContext().getLValueReferenceType(T);
2012
0
      llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2013
0
      assert(V && "Expression in template argument isn't constant");
2014
0
      llvm::DIType *TTy = getOrCreateType(T, Unit);
2015
0
      TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2016
0
          TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2017
0
    } break;
2018
    // And the following should never occur:
2019
0
    case TemplateArgument::TemplateExpansion:
2020
0
    case TemplateArgument::Null:
2021
0
      llvm_unreachable(
2022
199k
          "These argument types shouldn't exist in concrete types");
2023
199k
    }
2024
199k
  }
2025
118k
  return DBuilder.getOrCreateArray(TemplateParams);
2026
118k
}
2027
2028
llvm::DINodeArray
2029
CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2030
661k
                                           llvm::DIFile *Unit) {
2031
661k
  if (FD->getTemplatedKind() ==
2032
661k
      FunctionDecl::TK_FunctionTemplateSpecialization) {
2033
40.9k
    const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2034
40.9k
                                             ->getTemplate()
2035
40.9k
                                             ->getTemplateParameters();
2036
40.9k
    return CollectTemplateParams(
2037
40.9k
        TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
2038
40.9k
  }
2039
620k
  return llvm::DINodeArray();
2040
661k
}
2041
2042
llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2043
19
                                                        llvm::DIFile *Unit) {
2044
  // Always get the full list of parameters, not just the ones from the
2045
  // specialization. A partial specialization may have fewer parameters than
2046
  // there are arguments.
2047
19
  auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
2048
19
  if (!TS)
2049
0
    return llvm::DINodeArray();
2050
19
  VarTemplateDecl *T = TS->getSpecializedTemplate();
2051
19
  const TemplateParameterList *TList = T->getTemplateParameters();
2052
19
  auto TA = TS->getTemplateArgs().asArray();
2053
19
  return CollectTemplateParams(TList, TA, Unit);
2054
19
}
2055
2056
llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
2057
60.2k
    const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
2058
  // Always get the full list of parameters, not just the ones from the
2059
  // specialization. A partial specialization may have fewer parameters than
2060
  // there are arguments.
2061
60.2k
  TemplateParameterList *TPList =
2062
60.2k
      TSpecial->getSpecializedTemplate()->getTemplateParameters();
2063
60.2k
  const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2064
60.2k
  return CollectTemplateParams(TPList, TAList.asArray(), Unit);
2065
60.2k
}
2066
2067
418k
llvm::DINodeArray CGDebugInfo::CollectBTFTagAnnotations(const Decl *D) {
2068
418k
  if (!D->hasAttr<BTFTagAttr>())
2069
418k
    return nullptr;
2070
2071
6
  SmallVector<llvm::Metadata *, 4> Annotations;
2072
12
  for (const auto *I : D->specific_attrs<BTFTagAttr>()) {
2073
12
    llvm::Metadata *Ops[2] = {
2074
12
        llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_tag")),
2075
12
        llvm::MDString::get(CGM.getLLVMContext(), I->getBTFTag())};
2076
12
    Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2077
12
  }
2078
6
  return DBuilder.getOrCreateArray(Annotations);
2079
418k
}
2080
2081
873
llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2082
873
  if (VTablePtrType)
2083
484
    return VTablePtrType;
2084
2085
389
  ASTContext &Context = CGM.getContext();
2086
2087
  /* Function type */
2088
389
  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2089
389
  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2090
389
  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2091
389
  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2092
389
  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2093
389
  Optional<unsigned> DWARFAddressSpace =
2094
389
      CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2095
2096
389
  llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2097
389
      SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2098
389
  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2099
389
  return VTablePtrType;
2100
873
}
2101
2102
880
StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2103
  // Copy the gdb compatible name on the side and use its reference.
2104
880
  return internString("_vptr$", RD->getNameAsString());
2105
880
}
2106
2107
StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2108
                                                 DynamicInitKind StubKind,
2109
514
                                                 llvm::Function *InitFn) {
2110
  // If we're not emitting codeview, use the mangled name. For Itanium, this is
2111
  // arbitrary.
2112
514
  if (!CGM.getCodeGenOpts().EmitCodeView ||
2113
514
      
StubKind == DynamicInitKind::GlobalArrayDestructor22
)
2114
494
    return InitFn->getName();
2115
2116
  // Print the normal qualified name for the variable, then break off the last
2117
  // NNS, and add the appropriate other text. Clang always prints the global
2118
  // variable name without template arguments, so we can use rsplit("::") and
2119
  // then recombine the pieces.
2120
20
  SmallString<128> QualifiedGV;
2121
20
  StringRef Quals;
2122
20
  StringRef GVName;
2123
20
  {
2124
20
    llvm::raw_svector_ostream OS(QualifiedGV);
2125
20
    VD->printQualifiedName(OS, getPrintingPolicy());
2126
20
    std::tie(Quals, GVName) = OS.str().rsplit("::");
2127
20
    if (GVName.empty())
2128
15
      std::swap(Quals, GVName);
2129
20
  }
2130
2131
20
  SmallString<128> InitName;
2132
20
  llvm::raw_svector_ostream OS(InitName);
2133
20
  if (!Quals.empty())
2134
5
    OS << Quals << "::";
2135
2136
20
  switch (StubKind) {
2137
0
  case DynamicInitKind::NoStub:
2138
0
  case DynamicInitKind::GlobalArrayDestructor:
2139
0
    llvm_unreachable("not an initializer");
2140
13
  case DynamicInitKind::Initializer:
2141
13
    OS << "`dynamic initializer for '";
2142
13
    break;
2143
7
  case DynamicInitKind::AtExit:
2144
7
    OS << "`dynamic atexit destructor for '";
2145
7
    break;
2146
20
  }
2147
2148
20
  OS << GVName;
2149
2150
  // Add any template specialization args.
2151
20
  if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2152
2
    printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2153
2
                              getPrintingPolicy());
2154
2
  }
2155
2156
20
  OS << '\'';
2157
2158
20
  return internString(OS.str());
2159
20
}
2160
2161
void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2162
105k
                                    SmallVectorImpl<llvm::Metadata *> &EltTys) {
2163
  // If this class is not dynamic then there is not any vtable info to collect.
2164
105k
  if (!RD->isDynamicClass())
2165
102k
    return;
2166
2167
  // Don't emit any vtable shape or vptr info if this class doesn't have an
2168
  // extendable vfptr. This can happen if the class doesn't have virtual
2169
  // methods, or in the MS ABI if those virtual methods only come from virtually
2170
  // inherited bases.
2171
2.86k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2172
2.86k
  if (!RL.hasExtendableVFPtr())
2173
3
    return;
2174
2175
  // CodeView needs to know how large the vtable of every dynamic class is, so
2176
  // emit a special named pointer type into the element list. The vptr type
2177
  // points to this type as well.
2178
2.86k
  llvm::DIType *VPtrTy = nullptr;
2179
2.86k
  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2180
2.86k
                         
CGM.getTarget().getCXXABI().isMicrosoft()10
;
2181
2.86k
  if (NeedVTableShape) {
2182
10
    uint64_t PtrWidth =
2183
10
        CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2184
10
    const VTableLayout &VFTLayout =
2185
10
        CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2186
10
    unsigned VSlotCount =
2187
10
        VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2188
10
    unsigned VTableWidth = PtrWidth * VSlotCount;
2189
10
    unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2190
10
    Optional<unsigned> DWARFAddressSpace =
2191
10
        CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2192
2193
    // Create a very wide void* type and insert it directly in the element list.
2194
10
    llvm::DIType *VTableType = DBuilder.createPointerType(
2195
10
        nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2196
10
    EltTys.push_back(VTableType);
2197
2198
    // The vptr is a pointer to this special vtable type.
2199
10
    VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2200
10
  }
2201
2202
  // If there is a primary base then the artificial vptr member lives there.
2203
2.86k
  if (RL.getPrimaryBase())
2204
1.98k
    return;
2205
2206
880
  if (!VPtrTy)
2207
873
    VPtrTy = getOrCreateVTablePtrType(Unit);
2208
2209
880
  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2210
880
  llvm::DIType *VPtrMember =
2211
880
      DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2212
880
                                llvm::DINode::FlagArtificial, VPtrTy);
2213
880
  EltTys.push_back(VPtrMember);
2214
880
}
2215
2216
llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2217
3
                                                 SourceLocation Loc) {
2218
3
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2219
0
  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2220
3
  return T;
2221
3
}
2222
2223
llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2224
518
                                                    SourceLocation Loc) {
2225
518
  return getOrCreateStandaloneType(D, Loc);
2226
518
}
2227
2228
llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2229
168k
                                                     SourceLocation Loc) {
2230
168k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2231
0
  assert(!D.isNull() && "null type");
2232
0
  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2233
168k
  assert(T && "could not create debug info for type");
2234
2235
0
  RetainedTypes.push_back(D.getAsOpaquePtr());
2236
168k
  return T;
2237
168k
}
2238
2239
void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2240
                                           QualType AllocatedTy,
2241
694
                                           SourceLocation Loc) {
2242
694
  if (CGM.getCodeGenOpts().getDebugInfo() <=
2243
694
      codegenoptions::DebugLineTablesOnly)
2244
1
    return;
2245
693
  llvm::MDNode *node;
2246
693
  if (AllocatedTy->isVoidType())
2247
3
    node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2248
690
  else
2249
690
    node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2250
2251
693
  CI->setMetadata("heapallocsite", node);
2252
693
}
2253
2254
437k
void CGDebugInfo::completeType(const EnumDecl *ED) {
2255
437k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2256
14
    return;
2257
437k
  QualType Ty = CGM.getContext().getEnumType(ED);
2258
437k
  void *TyPtr = Ty.getAsOpaquePtr();
2259
437k
  auto I = TypeCache.find(TyPtr);
2260
437k
  if (I == TypeCache.end() || 
!cast<llvm::DIType>(I->second)->isForwardDecl()2.14k
)
2261
436k
    return;
2262
1.02k
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2263
1.02k
  assert(!Res->isForwardDecl());
2264
0
  TypeCache[TyPtr].reset(Res);
2265
1.02k
}
2266
2267
1.20M
void CGDebugInfo::completeType(const RecordDecl *RD) {
2268
1.20M
  if (DebugKind > codegenoptions::LimitedDebugInfo ||
2269
1.20M
      
!CGM.getLangOpts().CPlusPlus1.45k
)
2270
1.20M
    completeRequiredType(RD);
2271
1.20M
}
2272
2273
/// Return true if the class or any of its methods are marked dllimport.
2274
792
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2275
792
  if (RD->hasAttr<DLLImportAttr>())
2276
4
    return true;
2277
788
  for (const CXXMethodDecl *MD : RD->methods())
2278
2.87k
    if (MD->hasAttr<DLLImportAttr>())
2279
2
      return true;
2280
786
  return false;
2281
788
}
2282
2283
/// Does a type definition exist in an imported clang module?
2284
252k
static bool isDefinedInClangModule(const RecordDecl *RD) {
2285
  // Only definitions that where imported from an AST file come from a module.
2286
252k
  if (!RD || 
!RD->isFromASTFile()246k
)
2287
249k
    return false;
2288
  // Anonymous entities cannot be addressed. Treat them as not from module.
2289
3.20k
  if (!RD->isExternallyVisible() && 
RD->getName().empty()20
)
2290
16
    return false;
2291
3.19k
  if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2292
2.81k
    if (!CXXDecl->isCompleteDefinition())
2293
1
      return false;
2294
    // Check wether RD is a template.
2295
2.81k
    auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2296
2.81k
    if (TemplateKind != TSK_Undeclared) {
2297
      // Unfortunately getOwningModule() isn't accurate enough to find the
2298
      // owning module of a ClassTemplateSpecializationDecl that is inside a
2299
      // namespace spanning multiple modules.
2300
1.92k
      bool Explicit = false;
2301
1.92k
      if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2302
1.66k
        Explicit = TD->isExplicitInstantiationOrSpecialization();
2303
1.92k
      if (!Explicit && 
CXXDecl->getEnclosingNamespaceContext()1.77k
)
2304
1.77k
        return false;
2305
      // This is a template, check the origin of the first member.
2306
143
      if (CXXDecl->field_begin() == CXXDecl->field_end())
2307
112
        return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2308
31
      if (!CXXDecl->field_begin()->isFromASTFile())
2309
0
        return false;
2310
31
    }
2311
2.81k
  }
2312
1.29k
  return true;
2313
3.19k
}
2314
2315
3.15k
void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2316
3.15k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2317
2.97k
    if (CXXRD->isDynamicClass() &&
2318
2.97k
        CGM.getVTableLinkage(CXXRD) ==
2319
935
            llvm::GlobalValue::AvailableExternallyLinkage &&
2320
2.97k
        
!isClassOrMethodDLLImport(CXXRD)4
)
2321
3
      return;
2322
2323
3.14k
  if (DebugTypeExtRefs && 
isDefinedInClangModule(RD->getDefinition())1.82k
)
2324
5
    return;
2325
2326
3.14k
  completeClass(RD);
2327
3.14k
}
2328
2329
3.14k
void CGDebugInfo::completeClass(const RecordDecl *RD) {
2330
3.14k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2331
20
    return;
2332
3.12k
  QualType Ty = CGM.getContext().getRecordType(RD);
2333
3.12k
  void *TyPtr = Ty.getAsOpaquePtr();
2334
3.12k
  auto I = TypeCache.find(TyPtr);
2335
3.12k
  if (I != TypeCache.end() && 
!cast<llvm::DIType>(I->second)->isForwardDecl()3.11k
)
2336
629
    return;
2337
2.49k
  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2338
2.49k
  assert(!Res->isForwardDecl());
2339
0
  TypeCache[TyPtr].reset(Res);
2340
2.49k
}
2341
2342
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2343
38
                                        CXXRecordDecl::method_iterator End) {
2344
38
  for (CXXMethodDecl *MD : llvm::make_range(I, End))
2345
69
    if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2346
27
      if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2347
27
          
!MD->getMemberSpecializationInfo()->isExplicitSpecialization()10
)
2348
8
        return true;
2349
30
  return false;
2350
38
}
2351
2352
164
static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2353
  // Constructor homing can be used for classes that cannnot be constructed
2354
  // without emitting code for one of their constructors. This is classes that
2355
  // don't have trivial or constexpr constructors, or can be created from
2356
  // aggregate initialization. Also skip lambda objects because they don't call
2357
  // constructors.
2358
2359
  // Skip this optimization if the class or any of its methods are marked
2360
  // dllimport.
2361
164
  if (isClassOrMethodDLLImport(RD))
2362
0
    return false;
2363
2364
164
  return !RD->isLambda() && 
!RD->isAggregate()162
&&
2365
164
         
!RD->hasTrivialDefaultConstructor()64
&&
2366
164
         
!RD->hasConstexprNonCopyMoveConstructor()54
;
2367
164
}
2368
2369
static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2370
                                 bool DebugTypeExtRefs, const RecordDecl *RD,
2371
2.27M
                                 const LangOptions &LangOpts) {
2372
2.27M
  if (DebugTypeExtRefs && 
isDefinedInClangModule(RD->getDefinition())250k
)
2373
1.35k
    return true;
2374
2375
2.27M
  if (auto *ES = RD->getASTContext().getExternalSource())
2376
281k
    if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2377
9
      return true;
2378
2379
  // Only emit forward declarations in line tables only to keep debug info size
2380
  // small. This only applies to CodeView, since we don't emit types in DWARF
2381
  // line tables only.
2382
2.27M
  if (DebugKind == codegenoptions::DebugLineTablesOnly)
2383
129
    return true;
2384
2385
2.27M
  if (DebugKind > codegenoptions::LimitedDebugInfo ||
2386
2.27M
      
RD->hasAttr<StandaloneDebugAttr>()3.09k
)
2387
2.27M
    return false;
2388
2389
3.08k
  if (!LangOpts.CPlusPlus)
2390
898
    return false;
2391
2392
2.18k
  if (!RD->isCompleteDefinitionRequired())
2393
199
    return true;
2394
2395
1.98k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2396
2397
1.98k
  if (!CXXDecl)
2398
0
    return false;
2399
2400
  // Only emit complete debug info for a dynamic class when its vtable is
2401
  // emitted.  However, Microsoft debuggers don't resolve type information
2402
  // across DLL boundaries, so skip this optimization if the class or any of its
2403
  // methods are marked dllimport. This isn't a complete solution, since objects
2404
  // without any dllimport methods can be used in one DLL and constructed in
2405
  // another, but it is the current behavior of LimitedDebugInfo.
2406
1.98k
  if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2407
1.98k
      
!isClassOrMethodDLLImport(CXXDecl)624
)
2408
619
    return true;
2409
2410
1.36k
  TemplateSpecializationKind Spec = TSK_Undeclared;
2411
1.36k
  if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2412
591
    Spec = SD->getSpecializationKind();
2413
2414
1.36k
  if (Spec == TSK_ExplicitInstantiationDeclaration &&
2415
1.36k
      hasExplicitMemberDefinition(CXXDecl->method_begin(),
2416
38
                                  CXXDecl->method_end()))
2417
8
    return true;
2418
2419
  // In constructor homing mode, only emit complete debug info for a class
2420
  // when its constructor is emitted.
2421
1.35k
  if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2422
1.35k
      
canUseCtorHoming(CXXDecl)164
)
2423
28
    return true;
2424
2425
1.33k
  return false;
2426
1.35k
}
2427
2428
2.14M
void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2429
2.14M
  if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2430
708
    return;
2431
2432
2.14M
  QualType Ty = CGM.getContext().getRecordType(RD);
2433
2.14M
  llvm::DIType *T = getTypeOrNull(Ty);
2434
2.14M
  if (T && 
T->isForwardDecl()89.3k
)
2435
2.34k
    completeClassData(RD);
2436
2.14M
}
2437
2438
133k
llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2439
133k
  RecordDecl *RD = Ty->getDecl();
2440
133k
  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2441
133k
  if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2442
133k
                                CGM.getLangOpts())) {
2443
1.63k
    if (!T)
2444
1.63k
      T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2445
1.63k
    return T;
2446
1.63k
  }
2447
2448
132k
  return CreateTypeDefinition(Ty);
2449
133k
}
2450
2451
134k
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2452
134k
  RecordDecl *RD = Ty->getDecl();
2453
2454
  // Get overall information about the record type for the debug info.
2455
134k
  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2456
2457
  // Records and classes and unions can all be recursive.  To handle them, we
2458
  // first generate a debug descriptor for the struct as a forward declaration.
2459
  // Then (if it is a definition) we go through and get debug info for all of
2460
  // its members.  Finally, we create a descriptor for the complete type (which
2461
  // may refer to the forward decl if the struct is recursive) and replace all
2462
  // uses of the forward declaration with the final definition.
2463
134k
  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2464
2465
134k
  const RecordDecl *D = RD->getDefinition();
2466
134k
  if (!D || 
!D->isCompleteDefinition()121k
)
2467
13.0k
    return FwdDecl;
2468
2469
121k
  if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2470
105k
    CollectContainingType(CXXDecl, FwdDecl);
2471
2472
  // Push the struct on region stack.
2473
121k
  LexicalBlockStack.emplace_back(&*FwdDecl);
2474
121k
  RegionMap[Ty->getDecl()].reset(FwdDecl);
2475
2476
  // Convert all the elements.
2477
121k
  SmallVector<llvm::Metadata *, 16> EltTys;
2478
  // what about nested types?
2479
2480
  // Note: The split of CXXDecl information here is intentional, the
2481
  // gdb tests will depend on a certain ordering at printout. The debug
2482
  // information offsets are still correct if we merge them all together
2483
  // though.
2484
121k
  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2485
121k
  if (CXXDecl) {
2486
105k
    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2487
105k
    CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2488
105k
  }
2489
2490
  // Collect data fields (including static variables and any initializers).
2491
121k
  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2492
121k
  if (CXXDecl)
2493
105k
    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2494
2495
121k
  LexicalBlockStack.pop_back();
2496
121k
  RegionMap.erase(Ty->getDecl());
2497
2498
121k
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2499
121k
  DBuilder.replaceArrays(FwdDecl, Elements);
2500
2501
121k
  if (FwdDecl->isTemporary())
2502
0
    FwdDecl =
2503
0
        llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2504
2505
121k
  RegionMap[Ty->getDecl()].reset(FwdDecl);
2506
121k
  return FwdDecl;
2507
134k
}
2508
2509
llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2510
4.69k
                                      llvm::DIFile *Unit) {
2511
  // Ignore protocols.
2512
4.69k
  return getOrCreateType(Ty->getBaseType(), Unit);
2513
4.69k
}
2514
2515
llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2516
667
                                      llvm::DIFile *Unit) {
2517
  // Ignore protocols.
2518
667
  SourceLocation Loc = Ty->getDecl()->getLocation();
2519
2520
  // Use Typedefs to represent ObjCTypeParamType.
2521
667
  return DBuilder.createTypedef(
2522
667
      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2523
667
      Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2524
667
      getDeclContextDescriptor(Ty->getDecl()));
2525
667
}
2526
2527
/// \return true if Getter has the default name for the property PD.
2528
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2529
12.0k
                                 const ObjCMethodDecl *Getter) {
2530
12.0k
  assert(PD);
2531
12.0k
  if (!Getter)
2532
0
    return true;
2533
2534
12.0k
  assert(Getter->getDeclName().isObjCZeroArgSelector());
2535
0
  return PD->getName() ==
2536
12.0k
         Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2537
12.0k
}
2538
2539
/// \return true if Setter has the default name for the property PD.
2540
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2541
12.0k
                                 const ObjCMethodDecl *Setter) {
2542
12.0k
  assert(PD);
2543
12.0k
  if (!Setter)
2544
7.44k
    return true;
2545
2546
4.58k
  assert(Setter->getDeclName().isObjCOneArgSelector());
2547
0
  return SelectorTable::constructSetterName(PD->getName()) ==
2548
4.58k
         Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2549
12.0k
}
2550
2551
llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2552
4.08k
                                      llvm::DIFile *Unit) {
2553
4.08k
  ObjCInterfaceDecl *ID = Ty->getDecl();
2554
4.08k
  if (!ID)
2555
0
    return nullptr;
2556
2557
  // Return a forward declaration if this type was imported from a clang module,
2558
  // and this is not the compile unit with the implementation of the type (which
2559
  // may contain hidden ivars).
2560
4.08k
  if (DebugTypeExtRefs && 
ID->isFromASTFile()2.32k
&&
ID->getDefinition()682
&&
2561
4.08k
      
!ID->getImplementation()656
)
2562
650
    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2563
650
                                      ID->getName(),
2564
650
                                      getDeclContextDescriptor(ID), Unit, 0);
2565
2566
  // Get overall information about the record type for the debug info.
2567
3.43k
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2568
3.43k
  unsigned Line = getLineNumber(ID->getLocation());
2569
3.43k
  auto RuntimeLang =
2570
3.43k
      static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2571
2572
  // If this is just a forward declaration return a special forward-declaration
2573
  // debug type since we won't be able to lay out the entire type.
2574
3.43k
  ObjCInterfaceDecl *Def = ID->getDefinition();
2575
3.43k
  if (!Def || 
!Def->getImplementation()2.89k
) {
2576
2.92k
    llvm::DIScope *Mod = getParentModuleOrNull(ID);
2577
2.92k
    llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2578
2.92k
        llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? 
Mod1.49k
:
TheCU1.43k
,
2579
2.92k
        DefUnit, Line, RuntimeLang);
2580
2.92k
    ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2581
2.92k
    return FwdDecl;
2582
2.92k
  }
2583
2584
515
  return CreateTypeDefinition(Ty, Unit);
2585
3.43k
}
2586
2587
llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2588
596k
                                                  bool CreateSkeletonCU) {
2589
  // Use the Module pointer as the key into the cache. This is a
2590
  // nullptr if the "Module" is a PCH, which is safe because we don't
2591
  // support chained PCH debug info, so there can only be a single PCH.
2592
596k
  const Module *M = Mod.getModuleOrNull();
2593
596k
  auto ModRef = ModuleCache.find(M);
2594
596k
  if (ModRef != ModuleCache.end())
2595
570k
    return cast<llvm::DIModule>(ModRef->second);
2596
2597
  // Macro definitions that were defined with "-D" on the command line.
2598
25.4k
  SmallString<128> ConfigMacros;
2599
25.4k
  {
2600
25.4k
    llvm::raw_svector_ostream OS(ConfigMacros);
2601
25.4k
    const auto &PPOpts = CGM.getPreprocessorOpts();
2602
25.4k
    unsigned I = 0;
2603
    // Translate the macro definitions back into a command line.
2604
34.9k
    for (auto &M : PPOpts.Macros) {
2605
34.9k
      if (++I > 1)
2606
9.56k
        OS << " ";
2607
34.9k
      const std::string &Macro = M.first;
2608
34.9k
      bool Undef = M.second;
2609
34.9k
      OS << "\"-" << (Undef ? 
'U'1
:
'D'34.9k
);
2610
34.9k
      for (char c : Macro)
2611
864k
        switch (c) {
2612
0
        case '\\':
2613
0
          OS << "\\\\";
2614
0
          break;
2615
0
        case '"':
2616
0
          OS << "\\\"";
2617
0
          break;
2618
864k
        default:
2619
864k
          OS << c;
2620
864k
        }
2621
34.9k
      OS << '\"';
2622
34.9k
    }
2623
25.4k
  }
2624
2625
25.4k
  bool IsRootModule = M ? 
!M->Parent25.3k
:
true101
;
2626
  // When a module name is specified as -fmodule-name, that module gets a
2627
  // clang::Module object, but it won't actually be built or imported; it will
2628
  // be textual.
2629
25.4k
  if (CreateSkeletonCU && 
IsRootModule9.71k
&&
Mod.getASTFile().empty()1.50k
&&
M1
)
2630
1
    assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2631
25.4k
           "clang module without ASTFile must be specified by -fmodule-name");
2632
2633
  // Return a StringRef to the remapped Path.
2634
26.9k
  auto RemapPath = [this](StringRef Path) -> std::string {
2635
26.9k
    std::string Remapped = remapDIPath(Path);
2636
26.9k
    StringRef Relative(Remapped);
2637
26.9k
    StringRef CompDir = TheCU->getDirectory();
2638
26.9k
    if (Relative.consume_front(CompDir))
2639
94
      Relative.consume_front(llvm::sys::path::get_separator());
2640
2641
26.9k
    return Relative.str();
2642
26.9k
  };
2643
2644
25.4k
  if (CreateSkeletonCU && 
IsRootModule9.71k
&&
!Mod.getASTFile().empty()1.50k
) {
2645
    // PCH files don't have a signature field in the control block,
2646
    // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2647
    // We use the lower 64 bits for debug info.
2648
2649
1.50k
    uint64_t Signature = 0;
2650
1.50k
    if (const auto &ModSig = Mod.getSignature())
2651
1.48k
      Signature = ModSig.truncatedValue();
2652
15
    else
2653
15
      Signature = ~1ULL;
2654
2655
1.50k
    llvm::DIBuilder DIB(CGM.getModule());
2656
1.50k
    SmallString<0> PCM;
2657
1.50k
    if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2658
10
      PCM = Mod.getPath();
2659
1.50k
    llvm::sys::path::append(PCM, Mod.getASTFile());
2660
1.50k
    DIB.createCompileUnit(
2661
1.50k
        TheCU->getSourceLanguage(),
2662
        // TODO: Support "Source" from external AST providers?
2663
1.50k
        DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2664
1.50k
        TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2665
1.50k
        llvm::DICompileUnit::FullDebug, Signature);
2666
1.50k
    DIB.finalize();
2667
1.50k
  }
2668
2669
25.4k
  llvm::DIModule *Parent =
2670
25.4k
      IsRootModule ? 
nullptr1.82k
2671
25.4k
                   : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2672
23.6k
                                          CreateSkeletonCU);
2673
25.4k
  std::string IncludePath = Mod.getPath().str();
2674
25.4k
  llvm::DIModule *DIMod =
2675
25.4k
      DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2676
25.4k
                            RemapPath(IncludePath));
2677
25.4k
  ModuleCache[M].reset(DIMod);
2678
25.4k
  return DIMod;
2679
25.4k
}
2680
2681
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2682
3.24k
                                                llvm::DIFile *Unit) {
2683
3.24k
  ObjCInterfaceDecl *ID = Ty->getDecl();
2684
3.24k
  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2685
3.24k
  unsigned Line = getLineNumber(ID->getLocation());
2686
3.24k
  unsigned RuntimeLang = TheCU->getSourceLanguage();
2687
2688
  // Bit size, align and offset of the type.
2689
3.24k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2690
3.24k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2691
2692
3.24k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2693
3.24k
  if (ID->getImplementation())
2694
519
    Flags |= llvm::DINode::FlagObjcClassComplete;
2695
2696
3.24k
  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2697
3.24k
  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2698
3.24k
      Mod ? 
Mod1.33k
:
Unit1.91k
, ID->getName(), DefUnit, Line, Size, Align, Flags,
2699
3.24k
      nullptr, llvm::DINodeArray(), RuntimeLang);
2700
2701
3.24k
  QualType QTy(Ty, 0);
2702
3.24k
  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2703
2704
  // Push the struct on region stack.
2705
3.24k
  LexicalBlockStack.emplace_back(RealDecl);
2706
3.24k
  RegionMap[Ty->getDecl()].reset(RealDecl);
2707
2708
  // Convert all the elements.
2709
3.24k
  SmallVector<llvm::Metadata *, 16> EltTys;
2710
2711
3.24k
  ObjCInterfaceDecl *SClass = ID->getSuperClass();
2712
3.24k
  if (SClass) {
2713
2.86k
    llvm::DIType *SClassTy =
2714
2.86k
        getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2715
2.86k
    if (!SClassTy)
2716
0
      return nullptr;
2717
2718
2.86k
    llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2719
2.86k
                                                      llvm::DINode::FlagZero);
2720
2.86k
    EltTys.push_back(InhTag);
2721
2.86k
  }
2722
2723
  // Create entries for all of the properties.
2724
11.8k
  
auto AddProperty = [&](const ObjCPropertyDecl *PD) 3.24k
{
2725
11.8k
    SourceLocation Loc = PD->getLocation();
2726
11.8k
    llvm::DIFile *PUnit = getOrCreateFile(Loc);
2727
11.8k
    unsigned PLine = getLineNumber(Loc);
2728
11.8k
    ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2729
11.8k
    ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2730
11.8k
    llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2731
11.8k
        PD->getName(), PUnit, PLine,
2732
11.8k
        hasDefaultGetterName(PD, Getter) ? 
""11.2k
2733
11.8k
                                         : 
getSelectorName(PD->getGetterName())605
,
2734
11.8k
        hasDefaultSetterName(PD, Setter) ? 
""11.8k
2735
11.8k
                                         : 
getSelectorName(PD->getSetterName())5
,
2736
11.8k
        PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2737
11.8k
    EltTys.push_back(PropertyNode);
2738
11.8k
  };
2739
3.24k
  {
2740
    // Use 'char' for the isClassProperty bit as DenseSet requires space for
2741
    // empty/tombstone keys in the data type (and bool is too small for that).
2742
3.24k
    typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
2743
    /// List of already emitted properties. Two distinct class and instance
2744
    /// properties can share the same identifier (but not two instance
2745
    /// properties or two class properties).
2746
3.24k
    llvm::DenseSet<IsClassAndIdent> PropertySet;
2747
    /// Returns the IsClassAndIdent key for the given property.
2748
11.8k
    auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
2749
11.8k
      return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
2750
11.8k
    };
2751
3.24k
    for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2752
51
      for (auto *PD : ClassExt->properties()) {
2753
38
        PropertySet.insert(GetIsClassAndIdent(PD));
2754
38
        AddProperty(PD);
2755
38
      }
2756
11.7k
    for (const auto *PD : ID->properties()) {
2757
      // Don't emit duplicate metadata for properties that were already in a
2758
      // class extension.
2759
11.7k
      if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
2760
2
        continue;
2761
11.7k
      AddProperty(PD);
2762
11.7k
    }
2763
3.24k
  }
2764
2765
3.24k
  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2766
3.24k
  unsigned FieldNo = 0;
2767
7.27k
  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2768
4.03k
       Field = Field->getNextIvar(), ++FieldNo) {
2769
4.03k
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2770
4.03k
    if (!FieldTy)
2771
0
      return nullptr;
2772
2773
4.03k
    StringRef FieldName = Field->getName();
2774
2775
    // Ignore unnamed fields.
2776
4.03k
    if (FieldName.empty())
2777
14
      continue;
2778
2779
    // Get the location for the field.
2780
4.01k
    llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2781
4.01k
    unsigned FieldLine = getLineNumber(Field->getLocation());
2782
4.01k
    QualType FType = Field->getType();
2783
4.01k
    uint64_t FieldSize = 0;
2784
4.01k
    uint32_t FieldAlign = 0;
2785
2786
4.01k
    if (!FType->isIncompleteArrayType()) {
2787
2788
      // Bit size, align and offset of the type.
2789
4.01k
      FieldSize = Field->isBitField()
2790
4.01k
                      ? 
Field->getBitWidthValue(CGM.getContext())245
2791
4.01k
                      : 
CGM.getContext().getTypeSize(FType)3.77k
;
2792
4.01k
      FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2793
4.01k
    }
2794
2795
4.01k
    uint64_t FieldOffset;
2796
4.01k
    if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2797
      // We don't know the runtime offset of an ivar if we're using the
2798
      // non-fragile ABI.  For bitfields, use the bit offset into the first
2799
      // byte of storage of the bitfield.  For other fields, use zero.
2800
4.01k
      if (Field->isBitField()) {
2801
245
        FieldOffset =
2802
245
            CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2803
245
        FieldOffset %= CGM.getContext().getCharWidth();
2804
3.76k
      } else {
2805
3.76k
        FieldOffset = 0;
2806
3.76k
      }
2807
4.01k
    } else {
2808
6
      FieldOffset = RL.getFieldOffset(FieldNo);
2809
6
    }
2810
2811
4.01k
    llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2812
4.01k
    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2813
1.16k
      Flags = llvm::DINode::FlagProtected;
2814
2.85k
    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2815
2.69k
      Flags = llvm::DINode::FlagPrivate;
2816
157
    else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2817
121
      Flags = llvm::DINode::FlagPublic;
2818
2819
4.01k
    llvm::MDNode *PropertyNode = nullptr;
2820
4.01k
    if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2821
688
      if (ObjCPropertyImplDecl *PImpD =
2822
688
              ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2823
218
        if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2824
218
          SourceLocation Loc = PD->getLocation();
2825
218
          llvm::DIFile *PUnit = getOrCreateFile(Loc);
2826
218
          unsigned PLine = getLineNumber(Loc);
2827
218
          ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2828
218
          ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2829
218
          PropertyNode = DBuilder.createObjCProperty(
2830
218
              PD->getName(), PUnit, PLine,
2831
218
              hasDefaultGetterName(PD, Getter)
2832
218
                  ? 
""214
2833
218
                  : 
getSelectorName(PD->getGetterName())4
,
2834
218
              hasDefaultSetterName(PD, Setter)
2835
218
                  ? 
""214
2836
218
                  : 
getSelectorName(PD->getSetterName())4
,
2837
218
              PD->getPropertyAttributes(),
2838
218
              getOrCreateType(PD->getType(), PUnit));
2839
218
        }
2840
218
      }
2841
688
    }
2842
4.01k
    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2843
4.01k
                                      FieldSize, FieldAlign, FieldOffset, Flags,
2844
4.01k
                                      FieldTy, PropertyNode);
2845
4.01k
    EltTys.push_back(FieldTy);
2846
4.01k
  }
2847
2848
3.24k
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2849
3.24k
  DBuilder.replaceArrays(RealDecl, Elements);
2850
2851
3.24k
  LexicalBlockStack.pop_back();
2852
3.24k
  return RealDecl;
2853
3.24k
}
2854
2855
llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2856
1.40k
                                      llvm::DIFile *Unit) {
2857
1.40k
  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2858
1.40k
  int64_t Count = Ty->getNumElements();
2859
2860
1.40k
  llvm::Metadata *Subscript;
2861
1.40k
  QualType QTy(Ty, 0);
2862
1.40k
  auto SizeExpr = SizeExprCache.find(QTy);
2863
1.40k
  if (SizeExpr != SizeExprCache.end())
2864
0
    Subscript = DBuilder.getOrCreateSubrange(
2865
0
        SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2866
0
        nullptr /*upperBound*/, nullptr /*stride*/);
2867
1.40k
  else {
2868
1.40k
    auto *CountNode =
2869
1.40k
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2870
1.40k
            llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : 
-10
));
2871
1.40k
    Subscript = DBuilder.getOrCreateSubrange(
2872
1.40k
        CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2873
1.40k
        nullptr /*stride*/);
2874
1.40k
  }
2875
1.40k
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2876
2877
1.40k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2878
1.40k
  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2879
2880
1.40k
  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2881
1.40k
}
2882
2883
llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
2884
1
                                      llvm::DIFile *Unit) {
2885
  // FIXME: Create another debug type for matrices
2886
  // For the time being, it treats it like a nested ArrayType.
2887
2888
1
  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2889
1
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2890
1
  uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2891
2892
  // Create ranges for both dimensions.
2893
1
  llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
2894
1
  auto *ColumnCountNode =
2895
1
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2896
1
          llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
2897
1
  auto *RowCountNode =
2898
1
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2899
1
          llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
2900
1
  Subscripts.push_back(DBuilder.getOrCreateSubrange(
2901
1
      ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2902
1
      nullptr /*stride*/));
2903
1
  Subscripts.push_back(DBuilder.getOrCreateSubrange(
2904
1
      RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2905
1
      nullptr /*stride*/));
2906
1
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2907
1
  return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
2908
1
}
2909
2910
11.1k
llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2911
11.1k
  uint64_t Size;
2912
11.1k
  uint32_t Align;
2913
2914
  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2915
11.1k
  if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2916
43
    Size = 0;
2917
43
    Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2918
43
                                   CGM.getContext());
2919
11.1k
  } else if (Ty->isIncompleteArrayType()) {
2920
139
    Size = 0;
2921
139
    if (Ty->getElementType()->isIncompleteType())
2922
1
      Align = 0;
2923
138
    else
2924
138
      Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2925
11.0k
  } else if (Ty->isIncompleteType()) {
2926
2
    Size = 0;
2927
2
    Align = 0;
2928
11.0k
  } else {
2929
    // Size and align of the whole array, not the element type.
2930
11.0k
    Size = CGM.getContext().getTypeSize(Ty);
2931
11.0k
    Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2932
11.0k
  }
2933
2934
  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2935
  // interior arrays, do we care?  Why aren't nested arrays represented the
2936
  // obvious/recursive way?
2937
11.1k
  SmallVector<llvm::Metadata *, 8> Subscripts;
2938
11.1k
  QualType EltTy(Ty, 0);
2939
22.4k
  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2940
    // If the number of elements is known, then count is that number. Otherwise,
2941
    // it's -1. This allows us to represent a subrange with an array of 0
2942
    // elements, like this:
2943
    //
2944
    //   struct foo {
2945
    //     int x[0];
2946
    //   };
2947
11.2k
    int64_t Count = -1; // Count == -1 is an unbounded array.
2948
11.2k
    if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2949
11.0k
      Count = CAT->getSize().getZExtValue();
2950
183
    else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2951
44
      if (Expr *Size = VAT->getSizeExpr()) {
2952
43
        Expr::EvalResult Result;
2953
43
        if (Size->EvaluateAsInt(Result, CGM.getContext()))
2954
1
          Count = Result.Val.getInt().getExtValue();
2955
43
      }
2956
44
    }
2957
2958
11.2k
    auto SizeNode = SizeExprCache.find(EltTy);
2959
11.2k
    if (SizeNode != SizeExprCache.end())
2960
39
      Subscripts.push_back(DBuilder.getOrCreateSubrange(
2961
39
          SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
2962
39
          nullptr /*upperBound*/, nullptr /*stride*/));
2963
11.2k
    else {
2964
11.2k
      auto *CountNode =
2965
11.2k
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2966
11.2k
              llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
2967
11.2k
      Subscripts.push_back(DBuilder.getOrCreateSubrange(
2968
11.2k
          CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2969
11.2k
          nullptr /*stride*/));
2970
11.2k
    }
2971
11.2k
    EltTy = Ty->getElementType();
2972
11.2k
  }
2973
2974
11.1k
  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2975
2976
11.1k
  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2977
11.1k
                                  SubscriptArray);
2978
11.1k
}
2979
2980
llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2981
86.0k
                                      llvm::DIFile *Unit) {
2982
86.0k
  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2983
86.0k
                               Ty->getPointeeType(), Unit);
2984
86.0k
}
2985
2986
llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2987
19.2k
                                      llvm::DIFile *Unit) {
2988
19.2k
  llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
2989
  // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
2990
19.2k
  if (CGM.getCodeGenOpts().DebugStrictDwarf &&
2991
19.2k
      
CGM.getCodeGenOpts().DwarfVersion < 41.37k
)
2992
1.37k
    Tag = llvm::dwarf::DW_TAG_reference_type;
2993
2994
19.2k
  return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
2995
19.2k
}
2996
2997
llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2998
53
                                      llvm::DIFile *U) {
2999
53
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3000
53
  uint64_t Size = 0;
3001
3002
53
  if (!Ty->isIncompleteType()) {
3003
50
    Size = CGM.getContext().getTypeSize(Ty);
3004
3005
    // Set the MS inheritance model. There is no flag for the unspecified model.
3006
50
    if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3007
16
      switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3008
10
      case MSInheritanceModel::Single:
3009
10
        Flags |= llvm::DINode::FlagSingleInheritance;
3010
10
        break;
3011
2
      case MSInheritanceModel::Multiple:
3012
2
        Flags |= llvm::DINode::FlagMultipleInheritance;
3013
2
        break;
3014
2
      case MSInheritanceModel::Virtual:
3015
2
        Flags |= llvm::DINode::FlagVirtualInheritance;
3016
2
        break;
3017
2
      case MSInheritanceModel::Unspecified:
3018
2
        break;
3019
16
      }
3020
16
    }
3021
50
  }
3022
3023
53
  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3024
53
  if (Ty->isMemberDataPointerType())
3025
23
    return DBuilder.createMemberPointerType(
3026
23
        getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3027
23
        Flags);
3028
3029
30
  const FunctionProtoType *FPT =
3030
30
      Ty->getPointeeType()->getAs<FunctionProtoType>();
3031
30
  return DBuilder.createMemberPointerType(
3032
30
      getOrCreateInstanceMethodType(
3033
30
          CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3034
30
          FPT, U, false),
3035
30
      ClassType, Size, /*Align=*/0, Flags);
3036
53
}
3037
3038
976
llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3039
976
  auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3040
976
  return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3041
976
}
3042
3043
0
llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3044
0
  return getOrCreateType(Ty->getElementType(), U);
3045
0
}
3046
3047
14.3k
llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3048
14.3k
  const EnumDecl *ED = Ty->getDecl();
3049
3050
14.3k
  uint64_t Size = 0;
3051
14.3k
  uint32_t Align = 0;
3052
14.3k
  if (!ED->getTypeForDecl()->isIncompleteType()) {
3053
14.3k
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3054
14.3k
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
3055
14.3k
  }
3056
3057
14.3k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3058
3059
14.3k
  bool isImportedFromModule =
3060
14.3k
      DebugTypeExtRefs && 
ED->isFromASTFile()12.6k
&&
ED->getDefinition()198
;
3061
3062
  // If this is just a forward declaration, construct an appropriately
3063
  // marked node and just return it.
3064
14.3k
  if (isImportedFromModule || 
!ED->getDefinition()14.1k
) {
3065
    // Note that it is possible for enums to be created as part of
3066
    // their own declcontext. In this case a FwdDecl will be created
3067
    // twice. This doesn't cause a problem because both FwdDecls are
3068
    // entered into the ReplaceMap: finalize() will replace the first
3069
    // FwdDecl with the second and then replace the second with
3070
    // complete type.
3071
1.23k
    llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3072
1.23k
    llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3073
1.23k
    llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3074
1.23k
        llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3075
3076
1.23k
    unsigned Line = getLineNumber(ED->getLocation());
3077
1.23k
    StringRef EDName = ED->getName();
3078
1.23k
    llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3079
1.23k
        llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3080
1.23k
        0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3081
3082
1.23k
    ReplaceMap.emplace_back(
3083
1.23k
        std::piecewise_construct, std::make_tuple(Ty),
3084
1.23k
        std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3085
1.23k
    return RetTy;
3086
1.23k
  }
3087
3088
13.0k
  return CreateTypeDefinition(Ty);
3089
14.3k
}
3090
3091
14.1k
llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3092
14.1k
  const EnumDecl *ED = Ty->getDecl();
3093
14.1k
  uint64_t Size = 0;
3094
14.1k
  uint32_t Align = 0;
3095
14.1k
  if (!ED->getTypeForDecl()->isIncompleteType()) {
3096
14.1k
    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3097
14.1k
    Align = getDeclAlignIfRequired(ED, CGM.getContext());
3098
14.1k
  }
3099
3100
14.1k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3101
3102
14.1k
  SmallVector<llvm::Metadata *, 16> Enumerators;
3103
14.1k
  ED = ED->getDefinition();
3104
114k
  for (const auto *Enum : ED->enumerators()) {
3105
114k
    Enumerators.push_back(
3106
114k
        DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3107
114k
  }
3108
3109
  // Return a CompositeType for the enum itself.
3110
14.1k
  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3111
3112
14.1k
  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3113
14.1k
  unsigned Line = getLineNumber(ED->getLocation());
3114
14.1k
  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3115
14.1k
  llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3116
14.1k
  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3117
14.1k
                                        Line, Size, Align, EltArray, ClassTy,
3118
14.1k
                                        Identifier, ED->isScoped());
3119
14.1k
}
3120
3121
llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3122
                                        unsigned MType, SourceLocation LineLoc,
3123
1.34k
                                        StringRef Name, StringRef Value) {
3124
1.34k
  unsigned Line = LineLoc.isInvalid() ? 
01.30k
:
getLineNumber(LineLoc)45
;
3125
1.34k
  return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3126
1.34k
}
3127
3128
llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3129
                                                    SourceLocation LineLoc,
3130
20
                                                    SourceLocation FileLoc) {
3131
20
  llvm::DIFile *FName = getOrCreateFile(FileLoc);
3132
20
  unsigned Line = LineLoc.isInvalid() ? 
010
:
getLineNumber(LineLoc)10
;
3133
20
  return DBuilder.createTempMacroFile(Parent, Line, FName);
3134
20
}
3135
3136
10.1M
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3137
10.1M
  Qualifiers Quals;
3138
10.4M
  do {
3139
10.4M
    Qualifiers InnerQuals = T.getLocalQualifiers();
3140
    // Qualifiers::operator+() doesn't like it if you add a Qualifier
3141
    // that is already there.
3142
10.4M
    Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3143
10.4M
    Quals += InnerQuals;
3144
10.4M
    QualType LastT = T;
3145
10.4M
    switch (T->getTypeClass()) {
3146
10.1M
    default:
3147
10.1M
      return C.getQualifiedType(T.getTypePtr(), Quals);
3148
78.0k
    case Type::TemplateSpecialization: {
3149
78.0k
      const auto *Spec = cast<TemplateSpecializationType>(T);
3150
78.0k
      if (Spec->isTypeAlias())
3151
16.8k
        return C.getQualifiedType(T.getTypePtr(), Quals);
3152
61.1k
      T = Spec->desugar();
3153
61.1k
      break;
3154
78.0k
    }
3155
4
    case Type::TypeOfExpr:
3156
4
      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3157
4
      break;
3158
0
    case Type::TypeOf:
3159
0
      T = cast<TypeOfType>(T)->getUnderlyingType();
3160
0
      break;
3161
1.08k
    case Type::Decltype:
3162
1.08k
      T = cast<DecltypeType>(T)->getUnderlyingType();
3163
1.08k
      break;
3164
184
    case Type::UnaryTransform:
3165
184
      T = cast<UnaryTransformType>(T)->getUnderlyingType();
3166
184
      break;
3167
54.4k
    case Type::Attributed:
3168
54.4k
      T = cast<AttributedType>(T)->getEquivalentType();
3169
54.4k
      break;
3170
129k
    case Type::Elaborated:
3171
129k
      T = cast<ElaboratedType>(T)->getNamedType();
3172
129k
      break;
3173
15.3k
    case Type::Paren:
3174
15.3k
      T = cast<ParenType>(T)->getInnerType();
3175
15.3k
      break;
3176
783
    case Type::MacroQualified:
3177
783
      T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3178
783
      break;
3179
83.1k
    case Type::SubstTemplateTypeParm:
3180
83.1k
      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3181
83.1k
      break;
3182
331
    case Type::Auto:
3183
332
    case Type::DeducedTemplateSpecialization: {
3184
332
      QualType DT = cast<DeducedType>(T)->getDeducedType();
3185
332
      assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3186
0
      T = DT;
3187
332
      break;
3188
331
    }
3189
0
    case Type::Adjusted:
3190
8.72k
    case Type::Decayed:
3191
      // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3192
8.72k
      T = cast<AdjustedType>(T)->getAdjustedType();
3193
8.72k
      break;
3194
10.4M
    }
3195
3196
354k
    assert(T != LastT && "Type unwrapping failed to unwrap!");
3197
0
    (void)LastT;
3198
354k
  } while (true);
3199
10.1M
}
3200
3201
6.34M
llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3202
6.34M
  assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3203
0
  auto It = TypeCache.find(Ty.getAsOpaquePtr());
3204
6.34M
  if (It != TypeCache.end()) {
3205
    // Verify that the debug info still exists.
3206
2.77M
    if (llvm::Metadata *V = It->second)
3207
2.64M
      return cast<llvm::DIType>(V);
3208
2.77M
  }
3209
3210
3.69M
  return nullptr;
3211
6.34M
}
3212
3213
void CGDebugInfo::completeTemplateDefinition(
3214
9
    const ClassTemplateSpecializationDecl &SD) {
3215
9
  completeUnusedClass(SD);
3216
9
}
3217
3218
91
void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3219
91
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3220
4
    return;
3221
3222
87
  completeClassData(&D);
3223
  // In case this type has no member function definitions being emitted, ensure
3224
  // it is retained
3225
87
  RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3226
87
}
3227
3228
3.77M
llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3229
3.77M
  if (Ty.isNull())
3230
0
    return nullptr;
3231
3232
3.77M
  llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3233
0
    std::string Name;
3234
0
    llvm::raw_string_ostream OS(Name);
3235
0
    Ty.print(OS, getPrintingPolicy());
3236
0
    return Name;
3237
0
  });
3238
3239
  // Unwrap the type as needed for debug information.
3240
3.77M
  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3241
3242
3.77M
  if (auto *T = getTypeOrNull(Ty))
3243
2.54M
    return T;
3244
3245
1.23M
  llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3246
1.23M
  void *TyPtr = Ty.getAsOpaquePtr();
3247
3248
  // And update the type cache.
3249
1.23M
  TypeCache[TyPtr].reset(Res);
3250
3251
1.23M
  return Res;
3252
3.77M
}
3253
3254
1.05M
llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3255
  // A forward declaration inside a module header does not belong to the module.
3256
1.05M
  if (isa<RecordDecl>(D) && 
!cast<RecordDecl>(D)->getDefinition()205k
)
3257
12.7k
    return nullptr;
3258
1.03M
  if (DebugTypeExtRefs && 
D->isFromASTFile()529k
) {
3259
    // Record a reference to an imported clang module or precompiled header.
3260
20.6k
    auto *Reader = CGM.getContext().getExternalSource();
3261
20.6k
    auto Idx = D->getOwningModuleID();
3262
20.6k
    auto Info = Reader->getSourceDescriptor(Idx);
3263
20.6k
    if (Info)
3264
20.6k
      return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3265
1.01M
  } else if (ClangModuleMap) {
3266
    // We are building a clang module or a precompiled header.
3267
    //
3268
    // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3269
    // and it wouldn't be necessary to specify the parent scope
3270
    // because the type is already unique by definition (it would look
3271
    // like the output of -fno-standalone-debug). On the other hand,
3272
    // the parent scope helps a consumer to quickly locate the object
3273
    // file where the type's definition is located, so it might be
3274
    // best to make this behavior a command line or debugger tuning
3275
    // option.
3276
473k
    if (Module *M = D->getOwningModule()) {
3277
      // This is a (sub-)module.
3278
472k
      auto Info = ASTSourceDescriptor(*M);
3279
472k
      return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3280
472k
    } else {
3281
      // This the precompiled header being built.
3282
342
      return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3283
342
    }
3284
473k
  }
3285
3286
545k
  return nullptr;
3287
1.03M
}
3288
3289
1.23M
llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3290
  // Handle qualifiers, which recursively handles what they refer to.
3291
1.23M
  if (Ty.hasLocalQualifiers())
3292
73.1k
    return CreateQualifiedType(Ty, Unit);
3293
3294
  // Work out details of type.
3295
1.15M
  switch (Ty->getTypeClass()) {
3296
0
#define TYPE(Class, Base)
3297
0
#define ABSTRACT_TYPE(Class, Base)
3298
0
#define NON_CANONICAL_TYPE(Class, Base)
3299
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3300
0
#include "clang/AST/TypeNodes.inc"
3301
0
    llvm_unreachable("Dependent types cannot show up in debug information");
3302
3303
44
  case Type::ExtVector:
3304
1.40k
  case Type::Vector:
3305
1.40k
    return CreateType(cast<VectorType>(Ty), Unit);
3306
1
  case Type::ConstantMatrix:
3307
1
    return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3308
8.21k
  case Type::ObjCObjectPointer:
3309
8.21k
    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3310
4.69k
  case Type::ObjCObject:
3311
4.69k
    return CreateType(cast<ObjCObjectType>(Ty), Unit);
3312
667
  case Type::ObjCTypeParam:
3313
667
    return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3314
4.08k
  case Type::ObjCInterface:
3315
4.08k
    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3316
175k
  case Type::Builtin:
3317
175k
    return CreateType(cast<BuiltinType>(Ty));
3318
94
  case Type::Complex:
3319
94
    return CreateType(cast<ComplexType>(Ty));
3320
126k
  case Type::Pointer:
3321
126k
    return CreateType(cast<PointerType>(Ty), Unit);
3322
827
  case Type::BlockPointer:
3323
827
    return CreateType(cast<BlockPointerType>(Ty), Unit);
3324
185k
  case Type::Typedef:
3325
185k
    return CreateType(cast<TypedefType>(Ty), Unit);
3326
133k
  case Type::Record:
3327
133k
    return CreateType(cast<RecordType>(Ty));
3328
14.3k
  case Type::Enum:
3329
14.3k
    return CreateEnumType(cast<EnumType>(Ty));
3330
379k
  case Type::FunctionProto:
3331
379k
  case Type::FunctionNoProto:
3332
379k
    return CreateType(cast<FunctionType>(Ty), Unit);
3333
11.0k
  case Type::ConstantArray:
3334
11.0k
  case Type::VariableArray:
3335
11.1k
  case Type::IncompleteArray:
3336
11.1k
    return CreateType(cast<ArrayType>(Ty), Unit);
3337
3338
86.0k
  case Type::LValueReference:
3339
86.0k
    return CreateType(cast<LValueReferenceType>(Ty), Unit);
3340
19.2k
  case Type::RValueReference:
3341
19.2k
    return CreateType(cast<RValueReferenceType>(Ty), Unit);
3342
3343
53
  case Type::MemberPointer:
3344
53
    return CreateType(cast<MemberPointerType>(Ty), Unit);
3345
3346
976
  case Type::Atomic:
3347
976
    return CreateType(cast<AtomicType>(Ty), Unit);
3348
3349
0
  case Type::ExtInt:
3350
0
    return CreateType(cast<ExtIntType>(Ty));
3351
0
  case Type::Pipe:
3352
0
    return CreateType(cast<PipeType>(Ty), Unit);
3353
3354
7.08k
  case Type::TemplateSpecialization:
3355
7.08k
    return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3356
3357
0
  case Type::Auto:
3358
0
  case Type::Attributed:
3359
0
  case Type::Adjusted:
3360
0
  case Type::Decayed:
3361
0
  case Type::DeducedTemplateSpecialization:
3362
0
  case Type::Elaborated:
3363
0
  case Type::Paren:
3364
0
  case Type::MacroQualified:
3365
0
  case Type::SubstTemplateTypeParm:
3366
0
  case Type::TypeOfExpr:
3367
0
  case Type::TypeOf:
3368
0
  case Type::Decltype:
3369
0
  case Type::UnaryTransform:
3370
0
    break;
3371
1.15M
  }
3372
3373
0
  llvm_unreachable("type should have been unwrapped!");
3374
0
}
3375
3376
llvm::DICompositeType *
3377
134k
CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3378
134k
  QualType QTy(Ty, 0);
3379
3380
134k
  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3381
3382
  // We may have cached a forward decl when we could have created
3383
  // a non-forward decl. Go ahead and create a non-forward decl
3384
  // now.
3385
134k
  if (T && 
!T->isForwardDecl()2.48k
)
3386
0
    return T;
3387
3388
  // Otherwise create the type.
3389
134k
  llvm::DICompositeType *Res = CreateLimitedType(Ty);
3390
3391
  // Propagate members from the declaration to the definition
3392
  // CreateType(const RecordType*) will overwrite this with the members in the
3393
  // correct order if the full type is needed.
3394
134k
  DBuilder.replaceArrays(Res, T ? 
T->getElements()2.48k
:
llvm::DINodeArray()132k
);
3395
3396
  // And update the type cache.
3397
134k
  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3398
134k
  return Res;
3399
134k
}
3400
3401
// TODO: Currently used for context chains when limiting debug info.
3402
134k
llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3403
134k
  RecordDecl *RD = Ty->getDecl();
3404
3405
  // Get overall information about the record type for the debug info.
3406
134k
  StringRef RDName = getClassName(RD);
3407
134k
  const SourceLocation Loc = RD->getLocation();
3408
134k
  llvm::DIFile *DefUnit = nullptr;
3409
134k
  unsigned Line = 0;
3410
134k
  if (Loc.isValid()) {
3411
133k
    DefUnit = getOrCreateFile(Loc);
3412
133k
    Line = getLineNumber(Loc);
3413
133k
  }
3414
3415
134k
  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3416
3417
  // If we ended up creating the type during the context chain construction,
3418
  // just return that.
3419
134k
  auto *T = cast_or_null<llvm::DICompositeType>(
3420
134k
      getTypeOrNull(CGM.getContext().getRecordType(RD)));
3421
134k
  if (T && 
(2.51k
!T->isForwardDecl()2.51k
||
!RD->getDefinition()2.49k
))
3422
29
    return T;
3423
3424
  // If this is just a forward or incomplete declaration, construct an
3425
  // appropriately marked node and just return it.
3426
134k
  const RecordDecl *D = RD->getDefinition();
3427
134k
  if (!D || 
!D->isCompleteDefinition()121k
)
3428
13.0k
    return getOrCreateRecordFwdDecl(Ty, RDContext);
3429
3430
121k
  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3431
121k
  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3432
3433
121k
  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3434
3435
  // Explicitly record the calling convention and export symbols for C++
3436
  // records.
3437
121k
  auto Flags = llvm::DINode::FlagZero;
3438
121k
  if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3439
105k
    if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3440
11.5k
      Flags |= llvm::DINode::FlagTypePassByReference;
3441
93.5k
    else
3442
93.5k
      Flags |= llvm::DINode::FlagTypePassByValue;
3443
3444
    // Record if a C++ record is non-trivial type.
3445
105k
    if (!CXXRD->isTrivial())
3446
23.0k
      Flags |= llvm::DINode::FlagNonTrivial;
3447
3448
    // Record exports it symbols to the containing structure.
3449
105k
    if (CXXRD->isAnonymousStructOrUnion())
3450
641
        Flags |= llvm::DINode::FlagExportSymbols;
3451
105k
  }
3452
3453
121k
  llvm::DINodeArray Annotations = CollectBTFTagAnnotations(D);
3454
121k
  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3455
121k
      getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3456
121k
      Flags, Identifier, Annotations);
3457
3458
  // Elements of composite types usually have back to the type, creating
3459
  // uniquing cycles.  Distinct nodes are more efficient.
3460
121k
  switch (RealDecl->getTag()) {
3461
0
  default:
3462
0
    llvm_unreachable("invalid composite type tag");
3463
3464
0
  case llvm::dwarf::DW_TAG_array_type:
3465
0
  case llvm::dwarf::DW_TAG_enumeration_type:
3466
    // Array elements and most enumeration elements don't have back references,
3467
    // so they don't tend to be involved in uniquing cycles and there is some
3468
    // chance of merging them when linking together two modules.  Only make
3469
    // them distinct if they are ODR-uniqued.
3470
0
    if (Identifier.empty())
3471
0
      break;
3472
0
    LLVM_FALLTHROUGH;
3473
3474
98.9k
  case llvm::dwarf::DW_TAG_structure_type:
3475
101k
  case llvm::dwarf::DW_TAG_union_type:
3476
121k
  case llvm::dwarf::DW_TAG_class_type:
3477
    // Immediately resolve to a distinct node.
3478
121k
    RealDecl =
3479
121k
        llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3480
121k
    break;
3481
121k
  }
3482
3483
121k
  RegionMap[Ty->getDecl()].reset(RealDecl);
3484
121k
  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3485
3486
121k
  if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3487
60.2k
    DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3488
60.2k
                           CollectCXXTemplateParams(TSpecial, DefUnit));
3489
121k
  return RealDecl;
3490
121k
}
3491
3492
void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3493
105k
                                        llvm::DICompositeType *RealDecl) {
3494
  // A class's primary base or the class itself contains the vtable.
3495
105k
  llvm::DICompositeType *ContainingType = nullptr;
3496
105k
  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3497
105k
  if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3498
    // Seek non-virtual primary base root.
3499
3.53k
    while (1) {
3500
3.53k
      const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3501
3.53k
      const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3502
3.53k
      if (PBT && 
!BRL.isPrimaryBaseVirtual()1.56k
)
3503
1.55k
        PBase = PBT;
3504
1.98k
      else
3505
1.98k
        break;
3506
3.53k
    }
3507
1.98k
    ContainingType = cast<llvm::DICompositeType>(
3508
1.98k
        getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3509
1.98k
                        getOrCreateFile(RD->getLocation())));
3510
103k
  } else if (RD->isDynamicClass())
3511
883
    ContainingType = RealDecl;
3512
3513
105k
  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3514
105k
}
3515
3516
llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3517
5.17k
                                            StringRef Name, uint64_t *Offset) {
3518
5.17k
  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3519
5.17k
  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3520
5.17k
  auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3521
5.17k
  llvm::DIType *Ty =
3522
5.17k
      DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3523
5.17k
                                *Offset, llvm::DINode::FlagZero, FieldTy);
3524
5.17k
  *Offset += FieldSize;
3525
5.17k
  return Ty;
3526
5.17k
}
3527
3528
void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3529
                                           StringRef &Name,
3530
                                           StringRef &LinkageName,
3531
                                           llvm::DIScope *&FDContext,
3532
                                           llvm::DINodeArray &TParamsArray,
3533
300k
                                           llvm::DINode::DIFlags &Flags) {
3534
300k
  const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3535
300k
  Name = getFunctionName(FD);
3536
  // Use mangled name as linkage name for C/C++ functions.
3537
300k
  if (FD->getType()->getAs<FunctionProtoType>())
3538
299k
    LinkageName = CGM.getMangledName(GD);
3539
300k
  if (FD->hasPrototype())
3540
299k
    Flags |= llvm::DINode::FlagPrototyped;
3541
  // No need to replicate the linkage name if it isn't different from the
3542
  // subprogram name, no need to have it at all unless coverage is enabled or
3543
  // debug is set to more than just line tables or extra debug info is needed.
3544
300k
  if (LinkageName == Name || 
(134k
!CGM.getCodeGenOpts().EmitGcovArcs134k
&&
3545
134k
                              
!CGM.getCodeGenOpts().EmitGcovNotes134k
&&
3546
134k
                              
!CGM.getCodeGenOpts().DebugInfoForProfiling134k
&&
3547
134k
                              
!CGM.getCodeGenOpts().PseudoProbeForProfiling134k
&&
3548
134k
                              
DebugKind <= codegenoptions::DebugLineTablesOnly134k
))
3549
166k
    LinkageName = StringRef();
3550
3551
  // Emit the function scope in line tables only mode (if CodeView) to
3552
  // differentiate between function names.
3553
300k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3554
300k
      
(805
DebugKind == codegenoptions::DebugLineTablesOnly805
&&
3555
299k
       
CGM.getCodeGenOpts().EmitCodeView526
)) {
3556
299k
    if (const NamespaceDecl *NSDecl =
3557
299k
            dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3558
22.1k
      FDContext = getOrCreateNamespace(NSDecl);
3559
277k
    else if (const RecordDecl *RDecl =
3560
277k
                 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3561
69.1k
      llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3562
69.1k
      FDContext = getContextDescriptor(RDecl, Mod ? 
Mod2.80k
:
TheCU66.3k
);
3563
69.1k
    }
3564
299k
  }
3565
300k
  if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3566
    // Check if it is a noreturn-marked function
3567
299k
    if (FD->isNoReturn())
3568
2.75k
      Flags |= llvm::DINode::FlagNoReturn;
3569
    // Collect template parameters.
3570
299k
    TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3571
299k
  }
3572
300k
}
3573
3574
void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3575
                                      unsigned &LineNo, QualType &T,
3576
                                      StringRef &Name, StringRef &LinkageName,
3577
                                      llvm::MDTuple *&TemplateParameters,
3578
4.76k
                                      llvm::DIScope *&VDContext) {
3579
4.76k
  Unit = getOrCreateFile(VD->getLocation());
3580
4.76k
  LineNo = getLineNumber(VD->getLocation());
3581
3582
4.76k
  setLocation(VD->getLocation());
3583
3584
4.76k
  T = VD->getType();
3585
4.76k
  if (T->isIncompleteArrayType()) {
3586
    // CodeGen turns int[] into int[1] so we'll do the same here.
3587
0
    llvm::APInt ConstVal(32, 1);
3588
0
    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3589
3590
0
    T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3591
0
                                              ArrayType::Normal, 0);
3592
0
  }
3593
3594
4.76k
  Name = VD->getName();
3595
4.76k
  if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3596
4.76k
      
!isa<ObjCMethodDecl>(VD->getDeclContext())4.53k
)
3597
4.53k
    LinkageName = CGM.getMangledName(VD);
3598
4.76k
  if (LinkageName == Name)
3599
3.25k
    LinkageName = StringRef();
3600
3601
4.76k
  if (isa<VarTemplateSpecializationDecl>(VD)) {
3602
16
    llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3603
16
    TemplateParameters = parameterNodes.get();
3604
4.75k
  } else {
3605
4.75k
    TemplateParameters = nullptr;
3606
4.75k
  }
3607
3608
  // Since we emit declarations (DW_AT_members) for static members, place the
3609
  // definition of those static members in the namespace they were declared in
3610
  // in the source code (the lexical decl context).
3611
  // FIXME: Generalize this for even non-member global variables where the
3612
  // declaration and definition may have different lexical decl contexts, once
3613
  // we have support for emitting declarations of (non-member) global variables.
3614
4.76k
  const DeclContext *DC = VD->isStaticDataMember() ? 
VD->getLexicalDeclContext()106
3615
4.76k
                                                   : 
VD->getDeclContext()4.66k
;
3616
  // When a record type contains an in-line initialization of a static data
3617
  // member, and the record type is marked as __declspec(dllexport), an implicit
3618
  // definition of the member will be created in the record context.  DWARF
3619
  // doesn't seem to have a nice way to describe this in a form that consumers
3620
  // are likely to understand, so fake the "normal" situation of a definition
3621
  // outside the class by putting it in the global scope.
3622
4.76k
  if (DC->isRecord())
3623
1
    DC = CGM.getContext().getTranslationUnitDecl();
3624
3625
4.76k
  llvm::DIScope *Mod = getParentModuleOrNull(VD);
3626
4.76k
  VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? 
Mod28
:
TheCU4.73k
);
3627
4.76k
}
3628
3629
llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3630
83.8k
                                                          bool Stub) {
3631
83.8k
  llvm::DINodeArray TParamsArray;
3632
83.8k
  StringRef Name, LinkageName;
3633
83.8k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3634
83.8k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3635
83.8k
  SourceLocation Loc = GD.getDecl()->getLocation();
3636
83.8k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3637
83.8k
  llvm::DIScope *DContext = Unit;
3638
83.8k
  unsigned Line = getLineNumber(Loc);
3639
83.8k
  collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3640
83.8k
                           Flags);
3641
83.8k
  auto *FD = cast<FunctionDecl>(GD.getDecl());
3642
3643
  // Build function type.
3644
83.8k
  SmallVector<QualType, 16> ArgTypes;
3645
83.8k
  for (const ParmVarDecl *Parm : FD->parameters())
3646
157k
    ArgTypes.push_back(Parm->getType());
3647
3648
83.8k
  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3649
83.8k
  QualType FnType = CGM.getContext().getFunctionType(
3650
83.8k
      FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3651
83.8k
  if (!FD->isExternallyVisible())
3652
0
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3653
83.8k
  if (CGM.getLangOpts().Optimize)
3654
134
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3655
3656
83.8k
  if (Stub) {
3657
3
    Flags |= getCallSiteRelatedAttrs();
3658
3
    SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3659
3
    return DBuilder.createFunction(
3660
3
        DContext, Name, LinkageName, Unit, Line,
3661
3
        getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3662
3
        TParamsArray.get(), getFunctionDeclaration(FD));
3663
3
  }
3664
3665
83.8k
  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3666
83.8k
      DContext, Name, LinkageName, Unit, Line,
3667
83.8k
      getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3668
83.8k
      TParamsArray.get(), getFunctionDeclaration(FD));
3669
83.8k
  const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3670
83.8k
  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3671
83.8k
                                 std::make_tuple(CanonDecl),
3672
83.8k
                                 std::make_tuple(SP));
3673
83.8k
  return SP;
3674
83.8k
}
3675
3676
83.8k
llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3677
83.8k
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3678
83.8k
}
3679
3680
3
llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3681
3
  return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3682
3
}
3683
3684
llvm::DIGlobalVariable *
3685
4
CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3686
4
  QualType T;
3687
4
  StringRef Name, LinkageName;
3688
4
  SourceLocation Loc = VD->getLocation();
3689
4
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3690
4
  llvm::DIScope *DContext = Unit;
3691
4
  unsigned Line = getLineNumber(Loc);
3692
4
  llvm::MDTuple *TemplateParameters = nullptr;
3693
3694
4
  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3695
4
                      DContext);
3696
4
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3697
4
  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3698
4
      DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3699
4
      !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3700
4
  FwdDeclReplaceMap.emplace_back(
3701
4
      std::piecewise_construct,
3702
4
      std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3703
4
      std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3704
4
  return GV;
3705
4
}
3706
3707
110k
llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3708
  // We only need a declaration (not a definition) of the type - so use whatever
3709
  // we would otherwise do to get a type for a pointee. (forward declarations in
3710
  // limited debug info, full definitions (if the type definition is available)
3711
  // in unlimited debug info)
3712
110k
  if (const auto *TD = dyn_cast<TypeDecl>(D))
3713
24.3k
    return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3714
24.3k
                           getOrCreateFile(TD->getLocation()));
3715
86.2k
  auto I = DeclCache.find(D->getCanonicalDecl());
3716
3717
86.2k
  if (I != DeclCache.end()) {
3718
118
    auto N = I->second;
3719
118
    if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3720
79
      return GVE->getVariable();
3721
39
    return dyn_cast_or_null<llvm::DINode>(N);
3722
118
  }
3723
3724
  // No definition for now. Emit a forward definition that might be
3725
  // merged with a potential upcoming definition.
3726
86.1k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
3727
83.8k
    return getFunctionForwardDeclaration(FD);
3728
2.26k
  else if (const auto *VD = dyn_cast<VarDecl>(D))
3729
4
    return getGlobalVariableForwardDeclaration(VD);
3730
3731
2.25k
  return nullptr;
3732
86.1k
}
3733
3734
313k
llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3735
313k
  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3736
992
    return nullptr;
3737
3738
312k
  const auto *FD = dyn_cast<FunctionDecl>(D);
3739
312k
  if (!FD)
3740
13.1k
    return nullptr;
3741
3742
  // Setup context.
3743
299k
  auto *S = getDeclContextDescriptor(D);
3744
3745
299k
  auto MI = SPCache.find(FD->getCanonicalDecl());
3746
299k
  if (MI == SPCache.end()) {
3747
243k
    if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3748
12.4k
      return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3749
12.4k
                                     cast<llvm::DICompositeType>(S));
3750
12.4k
    }
3751
243k
  }
3752
287k
  if (MI != SPCache.end()) {
3753
56.6k
    auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3754
56.6k
    if (SP && !SP->isDefinition())
3755
56.6k
      return SP;
3756
56.6k
  }
3757
3758
236k
  
for (auto NextFD : FD->redecls())230k
{
3759
236k
    auto MI = SPCache.find(NextFD->getCanonicalDecl());
3760
236k
    if (MI != SPCache.end()) {
3761
0
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3762
0
      if (SP && !SP->isDefinition())
3763
0
        return SP;
3764
0
    }
3765
236k
  }
3766
230k
  return nullptr;
3767
230k
}
3768
3769
llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3770
    const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3771
1.32k
    llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3772
1.32k
  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3773
4
    return nullptr;
3774
3775
1.32k
  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3776
1.32k
  if (!OMD)
3777
0
    return nullptr;
3778
3779
1.32k
  if (CGM.getCodeGenOpts().DwarfVersion < 5 && 
!OMD->isDirectMethod()1.31k
)
3780
1.28k
    return nullptr;
3781
3782
31
  if (OMD->isDirectMethod())
3783
23
    SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3784
3785
  // Starting with DWARF V5 method declarations are emitted as children of
3786
  // the interface type.
3787
31
  auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3788
31
  if (!ID)
3789
31
    ID = OMD->getClassInterface();
3790
31
  if (!ID)
3791
0
    return nullptr;
3792
31
  QualType QTy(ID->getTypeForDecl(), 0);
3793
31
  auto It = TypeCache.find(QTy.getAsOpaquePtr());
3794
31
  if (It == TypeCache.end())
3795
0
    return nullptr;
3796
31
  auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3797
31
  llvm::DISubprogram *FD = DBuilder.createFunction(
3798
31
      InterfaceType, getObjCMethodName(OMD), StringRef(),
3799
31
      InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3800
31
  DBuilder.finalizeSubprogram(FD);
3801
31
  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3802
31
  return FD;
3803
31
}
3804
3805
// getOrCreateFunctionType - Construct type. If it is a c++ method, include
3806
// implicit parameter "this".
3807
llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3808
                                                             QualType FnType,
3809
315k
                                                             llvm::DIFile *F) {
3810
  // In CodeView, we emit the function types in line tables only because the
3811
  // only way to distinguish between functions is by display name and type.
3812
315k
  if (!D || 
(315k
DebugKind <= codegenoptions::DebugLineTablesOnly315k
&&
3813
315k
             
!CGM.getCodeGenOpts().EmitCodeView996
))
3814
    // Create fake but valid subroutine type. Otherwise -verify would fail, and
3815
    // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3816
1.70k
    return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3817
3818
314k
  if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3819
69.1k
    return getOrCreateMethodType(Method, F, false);
3820
3821
245k
  const auto *FTy = FnType->getAs<FunctionType>();
3822
245k
  CallingConv CC = FTy ? FTy->getCallConv() : 
CallingConv::CC_C0
;
3823
3824
245k
  if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3825
    // Add "self" and "_cmd"
3826
13.4k
    SmallVector<llvm::Metadata *, 16> Elts;
3827
3828
    // First element is always return type. For 'void' functions it is NULL.
3829
13.4k
    QualType ResultTy = OMethod->getReturnType();
3830
3831
    // Replace the instancetype keyword with the actual type.
3832
13.4k
    if (ResultTy == CGM.getContext().getObjCInstanceType())
3833
25
      ResultTy = CGM.getContext().getPointerType(
3834
25
          QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3835
3836
13.4k
    Elts.push_back(getOrCreateType(ResultTy, F));
3837
    // "self" pointer is always first argument.
3838
13.4k
    QualType SelfDeclTy;
3839
13.4k
    if (auto *SelfDecl = OMethod->getSelfDecl())
3840
13.4k
      SelfDeclTy = SelfDecl->getType();
3841
0
    else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3842
0
      if (FPT->getNumParams() > 1)
3843
0
        SelfDeclTy = FPT->getParamType(0);
3844
13.4k
    if (!SelfDeclTy.isNull())
3845
13.4k
      Elts.push_back(
3846
13.4k
          CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3847
    // "_cmd" pointer is always second argument.
3848
13.4k
    Elts.push_back(DBuilder.createArtificialType(
3849
13.4k
        getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3850
    // Get rest of the arguments.
3851
13.4k
    for (const auto *PI : OMethod->parameters())
3852
18.1k
      Elts.push_back(getOrCreateType(PI->getType(), F));
3853
    // Variadic methods need a special marker at the end of the type list.
3854
13.4k
    if (OMethod->isVariadic())
3855
74
      Elts.push_back(DBuilder.createUnspecifiedParameter());
3856
3857
13.4k
    llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3858
13.4k
    return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3859
13.4k
                                         getDwarfCC(CC));
3860
13.4k
  }
3861
3862
  // Handle variadic function types; they need an additional
3863
  // unspecified parameter.
3864
231k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
3865
230k
    if (FD->isVariadic()) {
3866
6.78k
      SmallVector<llvm::Metadata *, 16> EltTys;
3867
6.78k
      EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3868
6.78k
      if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3869
6.78k
        for (QualType ParamType : FPT->param_types())
3870
13.1k
          EltTys.push_back(getOrCreateType(ParamType, F));
3871
6.78k
      EltTys.push_back(DBuilder.createUnspecifiedParameter());
3872
6.78k
      llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3873
6.78k
      return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3874
6.78k
                                           getDwarfCC(CC));
3875
6.78k
    }
3876
3877
224k
  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3878
231k
}
3879
3880
void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3881
                                    SourceLocation ScopeLoc, QualType FnType,
3882
102k
                                    llvm::Function *Fn, bool CurFuncIsThunk) {
3883
102k
  StringRef Name;
3884
102k
  StringRef LinkageName;
3885
3886
102k
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
3887
3888
102k
  const Decl *D = GD.getDecl();
3889
102k
  bool HasDecl = (D != nullptr);
3890
3891
102k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3892
102k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3893
102k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3894
102k
  llvm::DIScope *FDContext = Unit;
3895
102k
  llvm::DINodeArray TParamsArray;
3896
102k
  if (!HasDecl) {
3897
    // Use llvm function name.
3898
739
    LinkageName = Fn->getName();
3899
101k
  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3900
    // If there is a subprogram for this function available then use it.
3901
99.0k
    auto FI = SPCache.find(FD->getCanonicalDecl());
3902
99.0k
    if (FI != SPCache.end()) {
3903
54.7k
      auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3904
54.7k
      if (SP && SP->isDefinition()) {
3905
0
        LexicalBlockStack.emplace_back(SP);
3906
0
        RegionMap[D].reset(SP);
3907
0
        return;
3908
0
      }
3909
54.7k
    }
3910
99.0k
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3911
99.0k
                             TParamsArray, Flags);
3912
99.0k
  } else 
if (const auto *2.52k
OMD2.52k
= dyn_cast<ObjCMethodDecl>(D)) {
3913
1.32k
    Name = getObjCMethodName(OMD);
3914
1.32k
    Flags |= llvm::DINode::FlagPrototyped;
3915
1.32k
  } else 
if (1.20k
isa<VarDecl>(D)1.20k
&&
3916
1.20k
             
GD.getDynamicInitKind() != DynamicInitKind::NoStub514
) {
3917
    // This is a global initializer or atexit destructor for a global variable.
3918
514
    Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3919
514
                                     Fn);
3920
691
  } else {
3921
691
    Name = Fn->getName();
3922
3923
691
    if (isa<BlockDecl>(D))
3924
175
      LinkageName = Name;
3925
3926
691
    Flags |= llvm::DINode::FlagPrototyped;
3927
691
  }
3928
102k
  if (Name.startswith("\01"))
3929
0
    Name = Name.substr(1);
3930
3931
102k
  if (!HasDecl || 
D->isImplicit()101k
||
D->hasAttr<ArtificialAttr>()98.3k
||
3932
102k
      
(98.3k
isa<VarDecl>(D)98.3k
&&
GD.getDynamicInitKind() != DynamicInitKind::NoStub513
)) {
3933
4.52k
    Flags |= llvm::DINode::FlagArtificial;
3934
    // Artificial functions should not silently reuse CurLoc.
3935
4.52k
    CurLoc = SourceLocation();
3936
4.52k
  }
3937
3938
102k
  if (CurFuncIsThunk)
3939
112
    Flags |= llvm::DINode::FlagThunk;
3940
3941
102k
  if (Fn->hasLocalLinkage())
3942
7.05k
    SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3943
102k
  if (CGM.getLangOpts().Optimize)
3944
1.40k
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3945
3946
102k
  llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3947
102k
  llvm::DISubprogram::DISPFlags SPFlagsForDef =
3948
102k
      SPFlags | llvm::DISubprogram::SPFlagDefinition;
3949
3950
102k
  const unsigned LineNo = getLineNumber(Loc.isValid() ? 
Loc101k
:
CurLoc1.00k
);
3951
102k
  unsigned ScopeLine = getLineNumber(ScopeLoc);
3952
102k
  llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3953
102k
  llvm::DISubprogram *Decl = nullptr;
3954
102k
  if (D)
3955
101k
    Decl = isa<ObjCMethodDecl>(D)
3956
101k
               ? 
getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)1.32k
3957
101k
               : 
getFunctionDeclaration(D)100k
;
3958
3959
  // FIXME: The function declaration we're constructing here is mostly reusing
3960
  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3961
  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3962
  // all subprograms instead of the actual context since subprogram definitions
3963
  // are emitted as CU level entities by the backend.
3964
102k
  llvm::DISubprogram *SP = DBuilder.createFunction(
3965
102k
      FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3966
102k
      FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3967
102k
  Fn->setSubprogram(SP);
3968
  // We might get here with a VarDecl in the case we're generating
3969
  // code for the initialization of globals. Do not record these decls
3970
  // as they will overwrite the actual VarDecl Decl in the cache.
3971
102k
  if (HasDecl && 
isa<FunctionDecl>(D)101k
)
3972
99.0k
    DeclCache[D->getCanonicalDecl()].reset(SP);
3973
3974
  // Push the function onto the lexical block stack.
3975
102k
  LexicalBlockStack.emplace_back(SP);
3976
3977
102k
  if (HasDecl)
3978
101k
    RegionMap[D].reset(SP);
3979
102k
}
3980
3981
void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3982
129k
                                   QualType FnType, llvm::Function *Fn) {
3983
129k
  StringRef Name;
3984
129k
  StringRef LinkageName;
3985
3986
129k
  const Decl *D = GD.getDecl();
3987
129k
  if (!D)
3988
0
    return;
3989
3990
129k
  llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3991
0
    return GetName(D, true);
3992
0
  });
3993
3994
129k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3995
129k
  llvm::DIFile *Unit = getOrCreateFile(Loc);
3996
129k
  bool IsDeclForCallSite = Fn ? 
true83
:
false129k
;
3997
129k
  llvm::DIScope *FDContext =
3998
129k
      IsDeclForCallSite ? 
Unit83
:
getDeclContextDescriptor(D)129k
;
3999
129k
  llvm::DINodeArray TParamsArray;
4000
129k
  if (isa<FunctionDecl>(D)) {
4001
    // If there is a DISubprogram for this function available then use it.
4002
117k
    collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4003
117k
                             TParamsArray, Flags);
4004
117k
  } else 
if (const auto *12.1k
OMD12.1k
= dyn_cast<ObjCMethodDecl>(D)) {
4005
12.1k
    Name = getObjCMethodName(OMD);
4006
12.1k
    Flags |= llvm::DINode::FlagPrototyped;
4007
12.1k
  } else {
4008
0
    llvm_unreachable("not a function or ObjC method");
4009
0
  }
4010
129k
  if (!Name.empty() && Name[0] == '\01')
4011
0
    Name = Name.substr(1);
4012
4013
129k
  if (D->isImplicit()) {
4014
0
    Flags |= llvm::DINode::FlagArtificial;
4015
    // Artificial functions without a location should not silently reuse CurLoc.
4016
0
    if (Loc.isInvalid())
4017
0
      CurLoc = SourceLocation();
4018
0
  }
4019
129k
  unsigned LineNo = getLineNumber(Loc);
4020
129k
  unsigned ScopeLine = 0;
4021
129k
  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4022
129k
  if (CGM.getLangOpts().Optimize)
4023
24.9k
    SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4024
4025
129k
  llvm::DISubprogram *SP = DBuilder.createFunction(
4026
129k
      FDContext, Name, LinkageName, Unit, LineNo,
4027
129k
      getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
4028
129k
      TParamsArray.get(), getFunctionDeclaration(D));
4029
4030
129k
  if (IsDeclForCallSite)
4031
83
    Fn->setSubprogram(SP);
4032
4033
129k
  DBuilder.finalizeSubprogram(SP);
4034
129k
}
4035
4036
void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4037
                                          QualType CalleeType,
4038
132k
                                          const FunctionDecl *CalleeDecl) {
4039
132k
  if (!CallOrInvoke)
4040
0
    return;
4041
132k
  auto *Func = CallOrInvoke->getCalledFunction();
4042
132k
  if (!Func)
4043
23
    return;
4044
132k
  if (Func->getSubprogram())
4045
15.8k
    return;
4046
4047
  // Do not emit a declaration subprogram for a builtin, a function with nodebug
4048
  // attribute, or if call site info isn't required. Also, elide declarations
4049
  // for functions with reserved names, as call site-related features aren't
4050
  // interesting in this case (& also, the compiler may emit calls to these
4051
  // functions without debug locations, which makes the verifier complain).
4052
116k
  if (CalleeDecl->getBuiltinID() != 0 || 
CalleeDecl->hasAttr<NoDebugAttr>()115k
||
4053
116k
      
getCallSiteRelatedAttrs() == llvm::DINode::FlagZero115k
)
4054
115k
    return;
4055
470
  if (CalleeDecl->isReserved(CGM.getLangOpts()) !=
4056
470
      ReservedIdentifierStatus::NotReserved)
4057
61
    return;
4058
4059
  // If there is no DISubprogram attached to the function being called,
4060
  // create the one describing the function in order to have complete
4061
  // call site debug info.
4062
409
  if (!CalleeDecl->isStatic() && 
!CalleeDecl->isInlined()304
)
4063
81
    EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4064
409
}
4065
4066
3
void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
4067
3
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
4068
  // If there is a subprogram for this function available then use it.
4069
3
  auto FI = SPCache.find(FD->getCanonicalDecl());
4070
3
  llvm::DISubprogram *SP = nullptr;
4071
3
  if (FI != SPCache.end())
4072
1
    SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4073
3
  if (!SP || 
!SP->isDefinition()1
)
4074
3
    SP = getFunctionStub(GD);
4075
3
  FnBeginRegionCount.push_back(LexicalBlockStack.size());
4076
3
  LexicalBlockStack.emplace_back(SP);
4077
3
  setInlinedAt(Builder.getCurrentDebugLocation());
4078
3
  EmitLocation(Builder, FD->getLocation());
4079
3
}
4080
4081
3
void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4082
3
  assert(CurInlinedAt && "unbalanced inline scope stack");
4083
0
  EmitFunctionEnd(Builder, nullptr);
4084
3
  setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4085
3
}
4086
4087
4.74M
void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4088
  // Update our current location
4089
4.74M
  setLocation(Loc);
4090
4091
4.74M
  if (CurLoc.isInvalid() || 
CurLoc.isMacroID()4.74M
||
LexicalBlockStack.empty()4.74M
)
4092
2.73k
    return;
4093
4094
4.74M
  llvm::MDNode *Scope = LexicalBlockStack.back();
4095
4.74M
  Builder.SetCurrentDebugLocation(
4096
4.74M
      llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4097
4.74M
                            getColumnNumber(CurLoc), Scope, CurInlinedAt));
4098
4.74M
}
4099
4100
207k
void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4101
207k
  llvm::MDNode *Back = nullptr;
4102
207k
  if (!LexicalBlockStack.empty())
4103
207k
    Back = LexicalBlockStack.back().get();
4104
207k
  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4105
207k
      cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4106
207k
      getColumnNumber(CurLoc)));
4107
207k
}
4108
4109
void CGDebugInfo::AppendAddressSpaceXDeref(
4110
280k
    unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
4111
280k
  Optional<unsigned> DWARFAddressSpace =
4112
280k
      CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4113
280k
  if (!DWARFAddressSpace)
4114
280k
    return;
4115
4116
111
  Expr.push_back(llvm::dwarf::DW_OP_constu);
4117
111
  Expr.push_back(DWARFAddressSpace.getValue());
4118
111
  Expr.push_back(llvm::dwarf::DW_OP_swap);
4119
111
  Expr.push_back(llvm::dwarf::DW_OP_xderef);
4120
111
}
4121
4122
void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4123
208k
                                        SourceLocation Loc) {
4124
  // Set our current location.
4125
208k
  setLocation(Loc);
4126
4127
  // Emit a line table change for the current location inside the new scope.
4128
208k
  Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4129
208k
      CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4130
208k
      LexicalBlockStack.back(), CurInlinedAt));
4131
4132
208k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4133
969
    return;
4134
4135
  // Create a new lexical block and push it on the stack.
4136
207k
  CreateLexicalBlock(Loc);
4137
207k
}
4138
4139
void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4140
208k
                                      SourceLocation Loc) {
4141
208k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4142
4143
  // Provide an entry in the line table for the end of the block.
4144
0
  EmitLocation(Builder, Loc);
4145
4146
208k
  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4147
969
    return;
4148
4149
207k
  LexicalBlockStack.pop_back();
4150
207k
}
4151
4152
102k
void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4153
102k
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4154
0
  unsigned RCount = FnBeginRegionCount.back();
4155
102k
  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4156
4157
  // Pop all regions for this function.
4158
204k
  while (LexicalBlockStack.size() != RCount) {
4159
    // Provide an entry in the line table for the end of the block.
4160
102k
    EmitLocation(Builder, CurLoc);
4161
102k
    LexicalBlockStack.pop_back();
4162
102k
  }
4163
102k
  FnBeginRegionCount.pop_back();
4164
4165
102k
  if (Fn && 
Fn->getSubprogram()102k
)
4166
102k
    DBuilder.finalizeSubprogram(Fn->getSubprogram());
4167
102k
}
4168
4169
CGDebugInfo::BlockByRefType
4170
CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4171
51
                                          uint64_t *XOffset) {
4172
51
  SmallVector<llvm::Metadata *, 5> EltTys;
4173
51
  QualType FType;
4174
51
  uint64_t FieldSize, FieldOffset;
4175
51
  uint32_t FieldAlign;
4176
4177
51
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4178
51
  QualType Type = VD->getType();
4179
4180
51
  FieldOffset = 0;
4181
51
  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4182
51
  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4183
51
  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4184
51
  FType = CGM.getContext().IntTy;
4185
51
  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4186
51
  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4187
4188
51
  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4189
51
  if (HasCopyAndDispose) {
4190
3
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4191
3
    EltTys.push_back(
4192
3
        CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4193
3
    EltTys.push_back(
4194
3
        CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4195
3
  }
4196
51
  bool HasByrefExtendedLayout;
4197
51
  Qualifiers::ObjCLifetime Lifetime;
4198
51
  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4199
51
                                        HasByrefExtendedLayout) &&
4200
51
      
HasByrefExtendedLayout21
) {
4201
6
    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4202
6
    EltTys.push_back(
4203
6
        CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4204
6
  }
4205
4206
51
  CharUnits Align = CGM.getContext().getDeclAlign(VD);
4207
51
  if (Align > CGM.getContext().toCharUnitsFromBits(
4208
51
                  CGM.getTarget().getPointerAlign(0))) {
4209
0
    CharUnits FieldOffsetInBytes =
4210
0
        CGM.getContext().toCharUnitsFromBits(FieldOffset);
4211
0
    CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4212
0
    CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4213
4214
0
    if (NumPaddingBytes.isPositive()) {
4215
0
      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4216
0
      FType = CGM.getContext().getConstantArrayType(
4217
0
          CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4218
0
      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4219
0
    }
4220
0
  }
4221
4222
51
  FType = Type;
4223
51
  llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4224
51
  FieldSize = CGM.getContext().getTypeSize(FType);
4225
51
  FieldAlign = CGM.getContext().toBits(Align);
4226
4227
51
  *XOffset = FieldOffset;
4228
51
  llvm::DIType *FieldTy = DBuilder.createMemberType(
4229
51
      Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4230
51
      llvm::DINode::FlagZero, WrappedTy);
4231
51
  EltTys.push_back(FieldTy);
4232
51
  FieldOffset += FieldSize;
4233
4234
51
  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4235
51
  return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4236
51
                                    llvm::DINode::FlagZero, nullptr, Elements),
4237
51
          WrappedTy};
4238
51
}
4239
4240
llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4241
                                                llvm::Value *Storage,
4242
                                                llvm::Optional<unsigned> ArgNo,
4243
                                                CGBuilderTy &Builder,
4244
276k
                                                const bool UsePointerValue) {
4245
276k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4246
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4247
276k
  if (VD->hasAttr<NoDebugAttr>())
4248
2
    return nullptr;
4249
4250
276k
  bool Unwritten =
4251
276k
      VD->isImplicit() || 
(206k
isa<Decl>(VD->getDeclContext())206k
&&
4252
206k
                           cast<Decl>(VD->getDeclContext())->isImplicit());
4253
276k
  llvm::DIFile *Unit = nullptr;
4254
276k
  if (!Unwritten)
4255
206k
    Unit = getOrCreateFile(VD->getLocation());
4256
276k
  llvm::DIType *Ty;
4257
276k
  uint64_t XOffset = 0;
4258
276k
  if (VD->hasAttr<BlocksAttr>())
4259
19
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4260
275k
  else
4261
275k
    Ty = getOrCreateType(VD->getType(), Unit);
4262
4263
  // If there is no debug info for this type then do not emit debug info
4264
  // for this variable.
4265
276k
  if (!Ty)
4266
0
    return nullptr;
4267
4268
  // Get location information.
4269
276k
  unsigned Line = 0;
4270
276k
  unsigned Column = 0;
4271
276k
  if (!Unwritten) {
4272
206k
    Line = getLineNumber(VD->getLocation());
4273
206k
    Column = getColumnNumber(VD->getLocation());
4274
206k
  }
4275
276k
  SmallVector<int64_t, 13> Expr;
4276
276k
  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4277
276k
  if (VD->isImplicit())
4278
69.5k
    Flags |= llvm::DINode::FlagArtificial;
4279
4280
276k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4281
4282
276k
  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4283
276k
  AppendAddressSpaceXDeref(AddressSpace, Expr);
4284
4285
  // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4286
  // object pointer flag.
4287
276k
  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4288
68.0k
    if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4289
68.0k
        
IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf3.97k
)
4290
65.3k
      Flags |= llvm::DINode::FlagObjectPointer;
4291
68.0k
  }
4292
4293
  // Note: Older versions of clang used to emit byval references with an extra
4294
  // DW_OP_deref, because they referenced the IR arg directly instead of
4295
  // referencing an alloca. Newer versions of LLVM don't treat allocas
4296
  // differently from other function arguments when used in a dbg.declare.
4297
276k
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4298
276k
  StringRef Name = VD->getName();
4299
276k
  if (!Name.empty()) {
4300
    // __block vars are stored on the heap if they are captured by a block that
4301
    // can escape the local scope.
4302
265k
    if (VD->isEscapingByref()) {
4303
      // Here, we need an offset *into* the alloca.
4304
14
      CharUnits offset = CharUnits::fromQuantity(32);
4305
14
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4306
      // offset of __forwarding field
4307
14
      offset = CGM.getContext().toCharUnitsFromBits(
4308
14
          CGM.getTarget().getPointerWidth(0));
4309
14
      Expr.push_back(offset.getQuantity());
4310
14
      Expr.push_back(llvm::dwarf::DW_OP_deref);
4311
14
      Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4312
      // offset of x field
4313
14
      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4314
14
      Expr.push_back(offset.getQuantity());
4315
14
    }
4316
265k
  } else 
if (const auto *10.3k
RT10.3k
= dyn_cast<RecordType>(VD->getType())) {
4317
    // If VD is an anonymous union then Storage represents value for
4318
    // all union fields.
4319
1.74k
    const RecordDecl *RD = RT->getDecl();
4320
1.74k
    if (RD->isUnion() && 
RD->isAnonymousStructOrUnion()4
) {
4321
      // GDB has trouble finding local variables in anonymous unions, so we emit
4322
      // artificial local variables for each of the members.
4323
      //
4324
      // FIXME: Remove this code as soon as GDB supports this.
4325
      // The debug info verifier in LLVM operates based on the assumption that a
4326
      // variable has the same size as its storage and we had to disable the
4327
      // check for artificial variables.
4328
8
      for (const auto *Field : RD->fields()) {
4329
8
        llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4330
8
        StringRef FieldName = Field->getName();
4331
4332
        // Ignore unnamed fields. Do not ignore unnamed records.
4333
8
        if (FieldName.empty() && 
!isa<RecordType>(Field->getType())0
)
4334
0
          continue;
4335
4336
        // Use VarDecl's Tag, Scope and Line number.
4337
8
        auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4338
8
        auto *D = DBuilder.createAutoVariable(
4339
8
            Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4340
8
            Flags | llvm::DINode::FlagArtificial, FieldAlign);
4341
4342
        // Insert an llvm.dbg.declare into the current block.
4343
8
        DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4344
8
                               llvm::DILocation::get(CGM.getLLVMContext(), Line,
4345
8
                                                     Column, Scope,
4346
8
                                                     CurInlinedAt),
4347
8
                               Builder.GetInsertBlock());
4348
8
      }
4349
4
    }
4350
1.74k
  }
4351
4352
  // Clang stores the sret pointer provided by the caller in a static alloca.
4353
  // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4354
  // the address of the variable.
4355
276k
  if (UsePointerValue) {
4356
154
    assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4357
154
               Expr.end() &&
4358
154
           "Debug info already contains DW_OP_deref.");
4359
0
    Expr.push_back(llvm::dwarf::DW_OP_deref);
4360
154
  }
4361
4362
  // Create the descriptor for the variable.
4363
0
  llvm::DILocalVariable *D = nullptr;
4364
276k
  if (ArgNo) {
4365
170k
    D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4366
170k
                                         CGM.getLangOpts().Optimize, Flags);
4367
170k
  } else {
4368
    // For normal local variable, we will try to find out whether 'VD' is the
4369
    // copy parameter of coroutine.
4370
    // If yes, we are going to use DIVariable of the origin parameter instead
4371
    // of creating the new one.
4372
    // If no, it might be a normal alloc, we just create a new one for it.
4373
4374
    // Check whether the VD is move parameters.
4375
105k
    auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4376
      // The scope of parameter and move-parameter should be distinct
4377
      // DISubprogram.
4378
105k
      if (!isa<llvm::DISubprogram>(Scope) || 
!Scope->isDistinct()35.7k
)
4379
69.5k
        return nullptr;
4380
4381
35.7k
      auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4382
9
        Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4383
9
        if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4384
9
          DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4385
9
          Decl *Decl = DeclGroup.getSingleDecl();
4386
9
          if (VD == dyn_cast_or_null<VarDecl>(Decl))
4387
3
            return true;
4388
9
        }
4389
6
        return false;
4390
9
      });
4391
4392
35.7k
      if (Iter != CoroutineParameterMappings.end()) {
4393
3
        ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4394
6
        auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4395
6
          return DbgPair.first == PD && 
DbgPair.second->getScope() == Scope3
;
4396
6
        });
4397
3
        if (Iter2 != ParamDbgMappings.end())
4398
3
          return const_cast<llvm::DILocalVariable *>(Iter2->second);
4399
3
      }
4400
35.7k
      return nullptr;
4401
35.7k
    };
4402
4403
    // If we couldn't find a move param DIVariable, create a new one.
4404
105k
    D = RemapCoroArgToLocalVar();
4405
    // Or we will create a new DIVariable for this Decl if D dose not exists.
4406
105k
    if (!D)
4407
105k
      D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4408
105k
                                      CGM.getLangOpts().Optimize, Flags, Align);
4409
105k
  }
4410
  // Insert an llvm.dbg.declare into the current block.
4411
276k
  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4412
276k
                         llvm::DILocation::get(CGM.getLLVMContext(), Line,
4413
276k
                                               Column, Scope, CurInlinedAt),
4414
276k
                         Builder.GetInsertBlock());
4415
4416
276k
  return D;
4417
276k
}
4418
4419
llvm::DILocalVariable *
4420
CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4421
                                       CGBuilderTy &Builder,
4422
105k
                                       const bool UsePointerValue) {
4423
105k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4424
0
  return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4425
105k
}
4426
4427
19
void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4428
19
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4429
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4430
4431
19
  if (D->hasAttr<NoDebugAttr>())
4432
0
    return;
4433
4434
19
  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4435
19
  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4436
4437
  // Get location information.
4438
19
  unsigned Line = getLineNumber(D->getLocation());
4439
19
  unsigned Column = getColumnNumber(D->getLocation());
4440
4441
19
  StringRef Name = D->getName();
4442
4443
  // Create the descriptor for the label.
4444
19
  auto *L =
4445
19
      DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4446
4447
  // Insert an llvm.dbg.label into the current block.
4448
19
  DBuilder.insertLabel(L,
4449
19
                       llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4450
19
                                             Scope, CurInlinedAt),
4451
19
                       Builder.GetInsertBlock());
4452
19
}
4453
4454
llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4455
13.4k
                                          llvm::DIType *Ty) {
4456
13.4k
  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4457
13.4k
  if (CachedTy)
4458
13.4k
    Ty = CachedTy;
4459
13.4k
  return DBuilder.createObjectPointerType(Ty);
4460
13.4k
}
4461
4462
void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4463
    const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4464
1.16k
    const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4465
1.16k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4466
0
  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4467
4468
1.16k
  if (Builder.GetInsertBlock() == nullptr)
4469
0
    return;
4470
1.16k
  if (VD->hasAttr<NoDebugAttr>())
4471
1
    return;
4472
4473
1.15k
  bool isByRef = VD->hasAttr<BlocksAttr>();
4474
4475
1.15k
  uint64_t XOffset = 0;
4476
1.15k
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4477
1.15k
  llvm::DIType *Ty;
4478
1.15k
  if (isByRef)
4479
16
    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4480
1.14k
  else
4481
1.14k
    Ty = getOrCreateType(VD->getType(), Unit);
4482
4483
  // Self is passed along as an implicit non-arg variable in a
4484
  // block. Mark it as the object pointer.
4485
1.15k
  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4486
10
    if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4487
10
      Ty = CreateSelfType(VD->getType(), Ty);
4488
4489
  // Get location information.
4490
1.15k
  const unsigned Line =
4491
1.15k
      getLineNumber(VD->getLocation().isValid() ? 
VD->getLocation()1.14k
:
CurLoc10
);
4492
1.15k
  unsigned Column = getColumnNumber(VD->getLocation());
4493
4494
1.15k
  const llvm::DataLayout &target = CGM.getDataLayout();
4495
4496
1.15k
  CharUnits offset = CharUnits::fromQuantity(
4497
1.15k
      target.getStructLayout(blockInfo.StructureType)
4498
1.15k
          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4499
4500
1.15k
  SmallVector<int64_t, 9> addr;
4501
1.15k
  addr.push_back(llvm::dwarf::DW_OP_deref);
4502
1.15k
  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4503
1.15k
  addr.push_back(offset.getQuantity());
4504
1.15k
  if (isByRef) {
4505
16
    addr.push_back(llvm::dwarf::DW_OP_deref);
4506
16
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4507
    // offset of __forwarding field
4508
16
    offset =
4509
16
        CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4510
16
    addr.push_back(offset.getQuantity());
4511
16
    addr.push_back(llvm::dwarf::DW_OP_deref);
4512
16
    addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4513
    // offset of x field
4514
16
    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4515
16
    addr.push_back(offset.getQuantity());
4516
16
  }
4517
4518
  // Create the descriptor for the variable.
4519
1.15k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4520
1.15k
  auto *D = DBuilder.createAutoVariable(
4521
1.15k
      cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4522
1.15k
      Line, Ty, false, llvm::DINode::FlagZero, Align);
4523
4524
  // Insert an llvm.dbg.declare into the current block.
4525
1.15k
  auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4526
1.15k
                                  LexicalBlockStack.back(), CurInlinedAt);
4527
1.15k
  auto *Expr = DBuilder.createExpression(addr);
4528
1.15k
  if (InsertPoint)
4529
1.15k
    DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4530
1
  else
4531
1
    DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4532
1.15k
}
4533
4534
llvm::DILocalVariable *
4535
CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4536
170k
                                      unsigned ArgNo, CGBuilderTy &Builder) {
4537
170k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4538
0
  return EmitDeclare(VD, AI, ArgNo, Builder);
4539
170k
}
4540
4541
namespace {
4542
struct BlockLayoutChunk {
4543
  uint64_t OffsetInBits;
4544
  const BlockDecl::Capture *Capture;
4545
};
4546
4.41k
bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4547
4.41k
  return l.OffsetInBits < r.OffsetInBits;
4548
4.41k
}
4549
} // namespace
4550
4551
void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4552
    const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4553
    const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4554
171
    SmallVectorImpl<llvm::Metadata *> &Fields) {
4555
  // Blocks in OpenCL have unique constraints which make the standard fields
4556
  // redundant while requiring size and align fields for enqueue_kernel. See
4557
  // initializeForBlockHeader in CGBlocks.cpp
4558
171
  if (CGM.getLangOpts().OpenCL) {
4559
7
    Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4560
7
                                     BlockLayout.getElementOffsetInBits(0),
4561
7
                                     Unit, Unit));
4562
7
    Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4563
7
                                     BlockLayout.getElementOffsetInBits(1),
4564
7
                                     Unit, Unit));
4565
164
  } else {
4566
164
    Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4567
164
                                     BlockLayout.getElementOffsetInBits(0),
4568
164
                                     Unit, Unit));
4569
164
    Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4570
164
                                     BlockLayout.getElementOffsetInBits(1),
4571
164
                                     Unit, Unit));
4572
164
    Fields.push_back(
4573
164
        createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4574
164
                        BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4575
164
    auto *FnTy = Block.getBlockExpr()->getFunctionType();
4576
164
    auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4577
164
    Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4578
164
                                     BlockLayout.getElementOffsetInBits(3),
4579
164
                                     Unit, Unit));
4580
164
    Fields.push_back(createFieldType(
4581
164
        "__descriptor",
4582
164
        Context.getPointerType(Block.NeedsCopyDispose
4583
164
                                   ? 
Context.getBlockDescriptorExtendedType()100
4584
164
                                   : 
Context.getBlockDescriptorType()64
),
4585
164
        Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4586
164
  }
4587
171
}
4588
4589
void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4590
                                                       StringRef Name,
4591
                                                       unsigned ArgNo,
4592
                                                       llvm::AllocaInst *Alloca,
4593
171
                                                       CGBuilderTy &Builder) {
4594
171
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4595
0
  ASTContext &C = CGM.getContext();
4596
171
  const BlockDecl *blockDecl = block.getBlockDecl();
4597
4598
  // Collect some general information about the block's location.
4599
171
  SourceLocation loc = blockDecl->getCaretLocation();
4600
171
  llvm::DIFile *tunit = getOrCreateFile(loc);
4601
171
  unsigned line = getLineNumber(loc);
4602
171
  unsigned column = getColumnNumber(loc);
4603
4604
  // Build the debug-info type for the block literal.
4605
171
  getDeclContextDescriptor(blockDecl);
4606
4607
171
  const llvm::StructLayout *blockLayout =
4608
171
      CGM.getDataLayout().getStructLayout(block.StructureType);
4609
4610
171
  SmallVector<llvm::Metadata *, 16> fields;
4611
171
  collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4612
171
                                             fields);
4613
4614
  // We want to sort the captures by offset, not because DWARF
4615
  // requires this, but because we're paranoid about debuggers.
4616
171
  SmallVector<BlockLayoutChunk, 8> chunks;
4617
4618
  // 'this' capture.
4619
171
  if (blockDecl->capturesCXXThis()) {
4620
1
    BlockLayoutChunk chunk;
4621
1
    chunk.OffsetInBits =
4622
1
        blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4623
1
    chunk.Capture = nullptr;
4624
1
    chunks.push_back(chunk);
4625
1
  }
4626
4627
  // Variable captures.
4628
1.16k
  for (const auto &capture : blockDecl->captures()) {
4629
1.16k
    const VarDecl *variable = capture.getVariable();
4630
1.16k
    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4631
4632
    // Ignore constant captures.
4633
1.16k
    if (captureInfo.isConstant())
4634
0
      continue;
4635
4636
1.16k
    BlockLayoutChunk chunk;
4637
1.16k
    chunk.OffsetInBits =
4638
1.16k
        blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4639
1.16k
    chunk.Capture = &capture;
4640
1.16k
    chunks.push_back(chunk);
4641
1.16k
  }
4642
4643
  // Sort by offset.
4644
171
  llvm::array_pod_sort(chunks.begin(), chunks.end());
4645
4646
1.16k
  for (const BlockLayoutChunk &Chunk : chunks) {
4647
1.16k
    uint64_t offsetInBits = Chunk.OffsetInBits;
4648
1.16k
    const BlockDecl::Capture *capture = Chunk.Capture;
4649
4650
    // If we have a null capture, this must be the C++ 'this' capture.
4651
1.16k
    if (!capture) {
4652
1
      QualType type;
4653
1
      if (auto *Method =
4654
1
              cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4655
0
        type = Method->getThisType();
4656
1
      else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4657
1
        type = QualType(RDecl->getTypeForDecl(), 0);
4658
0
      else
4659
0
        llvm_unreachable("unexpected block declcontext");
4660
4661
1
      fields.push_back(createFieldType("this", type, loc, AS_public,
4662
1
                                       offsetInBits, tunit, tunit));
4663
1
      continue;
4664
1
    }
4665
4666
1.16k
    const VarDecl *variable = capture->getVariable();
4667
1.16k
    StringRef name = variable->getName();
4668
4669
1.16k
    llvm::DIType *fieldType;
4670
1.16k
    if (capture->isByRef()) {
4671
16
      TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4672
16
      auto Align = PtrInfo.AlignIsRequired ? 
PtrInfo.Align0
: 0;
4673
      // FIXME: This recomputes the layout of the BlockByRefWrapper.
4674
16
      uint64_t xoffset;
4675
16
      fieldType =
4676
16
          EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4677
16
      fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4678
16
      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4679
16
                                            PtrInfo.Width, Align, offsetInBits,
4680
16
                                            llvm::DINode::FlagZero, fieldType);
4681
1.14k
    } else {
4682
1.14k
      auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4683
1.14k
      fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4684
1.14k
                                  offsetInBits, Align, tunit, tunit);
4685
1.14k
    }
4686
1.16k
    fields.push_back(fieldType);
4687
1.16k
  }
4688
4689
171
  SmallString<36> typeName;
4690
171
  llvm::raw_svector_ostream(typeName)
4691
171
      << "__block_literal_" << CGM.getUniqueBlockCount();
4692
4693
171
  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4694
4695
171
  llvm::DIType *type =
4696
171
      DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4697
171
                                CGM.getContext().toBits(block.BlockSize), 0,
4698
171
                                llvm::DINode::FlagZero, nullptr, fieldsArray);
4699
171
  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4700
4701
  // Get overall information about the block.
4702
171
  llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4703
171
  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4704
4705
  // Create the descriptor for the parameter.
4706
171
  auto *debugVar = DBuilder.createParameterVariable(
4707
171
      scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4708
4709
  // Insert an llvm.dbg.declare into the current block.
4710
171
  DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4711
171
                         llvm::DILocation::get(CGM.getLLVMContext(), line,
4712
171
                                               column, scope, CurInlinedAt),
4713
171
                         Builder.GetInsertBlock());
4714
171
}
4715
4716
llvm::DIDerivedType *
4717
4.82k
CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4718
4.82k
  if (!D || 
!D->isStaticDataMember()4.81k
)
4719
4.71k
    return nullptr;
4720
4721
106
  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4722
106
  if (MI != StaticDataMemberCache.end()) {
4723
27
    assert(MI->second && "Static data member declaration should still exist");
4724
0
    return MI->second;
4725
27
  }
4726
4727
  // If the member wasn't found in the cache, lazily construct and add it to the
4728
  // type (used when a limited form of the type is emitted).
4729
79
  auto DC = D->getDeclContext();
4730
79
  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4731
79
  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4732
106
}
4733
4734
llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4735
    const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4736
5
    StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4737
5
  llvm::DIGlobalVariableExpression *GVE = nullptr;
4738
4739
9
  for (const auto *Field : RD->fields()) {
4740
9
    llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4741
9
    StringRef FieldName = Field->getName();
4742
4743
    // Ignore unnamed fields, but recurse into anonymous records.
4744
9
    if (FieldName.empty()) {
4745
2
      if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4746
2
        GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4747
2
                                     Var, DContext);
4748
2
      continue;
4749
2
    }
4750
    // Use VarDecl's Tag, Scope and Line number.
4751
7
    GVE = DBuilder.createGlobalVariableExpression(
4752
7
        DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4753
7
        Var->hasLocalLinkage());
4754
7
    Var->addDebugInfo(GVE);
4755
7
  }
4756
5
  return GVE;
4757
5
}
4758
4759
736k
std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
4760
736k
  std::string Name;
4761
736k
  llvm::raw_string_ostream OS(Name);
4762
736k
  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
4763
736k
    PrintingPolicy PP = getPrintingPolicy();
4764
736k
    PP.PrintCanonicalTypes = true;
4765
736k
    PP.SuppressInlineNamespace = false;
4766
736k
    ND->getNameForDiagnostic(OS, PP, Qualified);
4767
736k
  }
4768
736k
  return Name;
4769
736k
}
4770
4771
void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4772
4.76k
                                     const VarDecl *D) {
4773
4.76k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4774
4.76k
  if (D->hasAttr<NoDebugAttr>())
4775
4
    return;
4776
4777
4.76k
  llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4778
0
    return GetName(D, true);
4779
0
  });
4780
4781
  // If we already created a DIGlobalVariable for this declaration, just attach
4782
  // it to the llvm::GlobalVariable.
4783
4.76k
  auto Cached = DeclCache.find(D->getCanonicalDecl());
4784
4.76k
  if (Cached != DeclCache.end())
4785
3
    return Var->addDebugInfo(
4786
3
        cast<llvm::DIGlobalVariableExpression>(Cached->second));
4787
4788
  // Create global variable debug descriptor.
4789
4.76k
  llvm::DIFile *Unit = nullptr;
4790
4.76k
  llvm::DIScope *DContext = nullptr;
4791
4.76k
  unsigned LineNo;
4792
4.76k
  StringRef DeclName, LinkageName;
4793
4.76k
  QualType T;
4794
4.76k
  llvm::MDTuple *TemplateParameters = nullptr;
4795
4.76k
  collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4796
4.76k
                      TemplateParameters, DContext);
4797
4798
  // Attempt to store one global variable for the declaration - even if we
4799
  // emit a lot of fields.
4800
4.76k
  llvm::DIGlobalVariableExpression *GVE = nullptr;
4801
4802
  // If this is an anonymous union then we'll want to emit a global
4803
  // variable for each member of the anonymous union so that it's possible
4804
  // to find the name of any field in the union.
4805
4.76k
  if (T->isUnionType() && 
DeclName.empty()22
) {
4806
3
    const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4807
3
    assert(RD->isAnonymousStructOrUnion() &&
4808
3
           "unnamed non-anonymous struct or union?");
4809
0
    GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4810
4.75k
  } else {
4811
4.75k
    auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4812
4813
4.75k
    SmallVector<int64_t, 4> Expr;
4814
4.75k
    unsigned AddressSpace =
4815
4.75k
        CGM.getContext().getTargetAddressSpace(D->getType());
4816
4.75k
    if (CGM.getLangOpts().CUDA && 
CGM.getLangOpts().CUDAIsDevice4
) {
4817
4
      if (D->hasAttr<CUDASharedAttr>())
4818
2
        AddressSpace =
4819
2
            CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4820
2
      else if (D->hasAttr<CUDAConstantAttr>())
4821
1
        AddressSpace =
4822
1
            CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4823
4
    }
4824
4.75k
    AppendAddressSpaceXDeref(AddressSpace, Expr);
4825
4826
4.75k
    GVE = DBuilder.createGlobalVariableExpression(
4827
4.75k
        DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4828
4.75k
        Var->hasLocalLinkage(), true,
4829
4.75k
        Expr.empty() ? 
nullptr4.72k
:
DBuilder.createExpression(Expr)34
,
4830
4.75k
        getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4831
4.75k
        Align);
4832
4.75k
    Var->addDebugInfo(GVE);
4833
4.75k
  }
4834
0
  DeclCache[D->getCanonicalDecl()].reset(GVE);
4835
4.76k
}
4836
4837
3.58k
void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4838
3.58k
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4839
3.58k
  if (VD->hasAttr<NoDebugAttr>())
4840
2
    return;
4841
3.58k
  llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4842
0
    return GetName(VD, true);
4843
0
  });
4844
4845
3.58k
  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4846
  // Create the descriptor for the variable.
4847
3.58k
  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4848
3.58k
  StringRef Name = VD->getName();
4849
3.58k
  llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4850
4851
3.58k
  if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4852
741
    const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4853
741
    assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4854
4855
741
    if (CGM.getCodeGenOpts().EmitCodeView) {
4856
      // If CodeView, emit enums as global variables, unless they are defined
4857
      // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4858
      // enums in classes, and because it is difficult to attach this scope
4859
      // information to the global variable.
4860
5
      if (isa<RecordDecl>(ED->getDeclContext()))
4861
0
        return;
4862
736
    } else {
4863
      // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4864
      // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4865
      // first time `ZERO` is referenced in a function.
4866
736
      llvm::DIType *EDTy =
4867
736
          getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4868
736
      assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4869
0
      (void)EDTy;
4870
736
      return;
4871
736
    }
4872
741
  }
4873
4874
  // Do not emit separate definitions for function local consts.
4875
2.84k
  if (isa<FunctionDecl>(VD->getDeclContext()))
4876
393
    return;
4877
4878
2.45k
  VD = cast<ValueDecl>(VD->getCanonicalDecl());
4879
2.45k
  auto *VarD = dyn_cast<VarDecl>(VD);
4880
2.45k
  if (VarD && 
VarD->isStaticDataMember()2.45k
) {
4881
2.37k
    auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4882
2.37k
    getDeclContextDescriptor(VarD);
4883
    // Ensure that the type is retained even though it's otherwise unreferenced.
4884
    //
4885
    // FIXME: This is probably unnecessary, since Ty should reference RD
4886
    // through its scope.
4887
2.37k
    RetainedTypes.push_back(
4888
2.37k
        CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4889
4890
2.37k
    return;
4891
2.37k
  }
4892
79
  llvm::DIScope *DContext = getDeclContextDescriptor(VD);
4893
4894
79
  auto &GV = DeclCache[VD];
4895
79
  if (GV)
4896
17
    return;
4897
62
  llvm::DIExpression *InitExpr = nullptr;
4898
62
  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4899
    // FIXME: Add a representation for integer constants wider than 64 bits.
4900
57
    if (Init.isInt())
4901
43
      InitExpr =
4902
43
          DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4903
14
    else if (Init.isFloat())
4904
10
      InitExpr = DBuilder.createConstantValueExpression(
4905
10
          Init.getFloat().bitcastToAPInt().getZExtValue());
4906
57
  }
4907
4908
62
  llvm::MDTuple *TemplateParameters = nullptr;
4909
4910
62
  if (isa<VarTemplateSpecializationDecl>(VD))
4911
3
    if (VarD) {
4912
3
      llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4913
3
      TemplateParameters = parameterNodes.get();
4914
3
    }
4915
4916
62
  GV.reset(DBuilder.createGlobalVariableExpression(
4917
62
      DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4918
62
      true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4919
62
      TemplateParameters, Align));
4920
62
}
4921
4922
void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4923
7
                                       const VarDecl *D) {
4924
7
  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4925
7
  if (D->hasAttr<NoDebugAttr>())
4926
0
    return;
4927
4928
7
  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4929
7
  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4930
7
  StringRef Name = D->getName();
4931
7
  llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4932
4933
7
  llvm::DIScope *DContext = getDeclContextDescriptor(D);
4934
7
  llvm::DIGlobalVariableExpression *GVE =
4935
7
      DBuilder.createGlobalVariableExpression(
4936
7
          DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4937
7
          Ty, false, false, nullptr, nullptr, nullptr, Align);
4938
7
  Var->addDebugInfo(GVE);
4939
7
}
4940
4941
187k
llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4942
187k
  if (!LexicalBlockStack.empty())
4943
179
    return LexicalBlockStack.back();
4944
187k
  llvm::DIScope *Mod = getParentModuleOrNull(D);
4945
187k
  return getContextDescriptor(D, Mod ? 
Mod77.6k
:
TheCU109k
);
4946
187k
}
4947
4948
833
void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4949
833
  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4950
11
    return;
4951
822
  const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4952
822
  if (!NSDecl->isAnonymousNamespace() ||
4953
822
      
CGM.getCodeGenOpts().DebugExplicitImport510
) {
4954
314
    auto Loc = UD.getLocation();
4955
314
    if (!Loc.isValid())
4956
2
      Loc = CurLoc;
4957
314
    DBuilder.createImportedModule(
4958
314
        getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4959
314
        getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4960
314
  }
4961
822
}
4962
4963
110k
void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
4964
110k
  if (llvm::DINode *Target =
4965
110k
          getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4966
108k
    auto Loc = USD.getLocation();
4967
108k
    DBuilder.createImportedDeclaration(
4968
108k
        getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4969
108k
        getOrCreateFile(Loc), getLineNumber(Loc));
4970
108k
  }
4971
110k
}
4972
4973
110k
void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4974
110k
  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4975
20
    return;
4976
110k
  assert(UD.shadow_size() &&
4977
110k
         "We shouldn't be codegening an invalid UsingDecl containing no decls");
4978
4979
110k
  for (const auto *USD : UD.shadows()) {
4980
    // FIXME: Skip functions with undeduced auto return type for now since we
4981
    // don't currently have the plumbing for separate declarations & definitions
4982
    // of free functions and mismatched types (auto in the declaration, concrete
4983
    // return type in the definition)
4984
110k
    if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
4985
83.9k
      if (const auto *AT = FD->getType()
4986
83.9k
                               ->castAs<FunctionProtoType>()
4987
83.9k
                               ->getContainedAutoType())
4988
2
        if (AT->getDeducedType().isNull())
4989
1
          continue;
4990
4991
110k
    EmitUsingShadowDecl(*USD);
4992
    // Emitting one decl is sufficient - debuggers can detect that this is an
4993
    // overloaded name & provide lookup for all the overloads.
4994
110k
    break;
4995
110k
  }
4996
110k
}
4997
4998
0
void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
4999
0
  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5000
0
    return;
5001
0
  assert(UD.shadow_size() &&
5002
0
         "We shouldn't be codegening an invalid UsingEnumDecl"
5003
0
         " containing no decls");
5004
5005
0
  for (const auto *USD : UD.shadows())
5006
0
    EmitUsingShadowDecl(*USD);
5007
0
}
5008
5009
78.7k
void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
5010
78.7k
  if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5011
109
    return;
5012
78.6k
  if (Module *M = ID.getImportedModule()) {
5013
78.6k
    auto Info = ASTSourceDescriptor(*M);
5014
78.6k
    auto Loc = ID.getLocation();
5015
78.6k
    DBuilder.createImportedDeclaration(
5016
78.6k
        getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5017
78.6k
        getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5018
78.6k
        getLineNumber(Loc));
5019
78.6k
  }
5020
78.6k
}
5021
5022
llvm::DIImportedEntity *
5023
50
CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
5024
50
  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5025
6
    return nullptr;
5026
44
  auto &VH = NamespaceAliasCache[&NA];
5027
44
  if (VH)
5028
2
    return cast<llvm::DIImportedEntity>(VH);
5029
42
  llvm::DIImportedEntity *R;
5030
42
  auto Loc = NA.getLocation();
5031
42
  if (const auto *Underlying =
5032
42
          dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
5033
    // This could cache & dedup here rather than relying on metadata deduping.
5034
2
    R = DBuilder.createImportedDeclaration(
5035
2
        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5036
2
        EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
5037
2
        getLineNumber(Loc), NA.getName());
5038
40
  else
5039
40
    R = DBuilder.createImportedDeclaration(
5040
40
        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5041
40
        getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
5042
40
        getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
5043
42
  VH.reset(R);
5044
42
  return R;
5045
44
}
5046
5047
llvm::DINamespace *
5048
259k
CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
5049
  // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5050
  // if necessary, and this way multiple declarations of the same namespace in
5051
  // different parent modules stay distinct.
5052
259k
  auto I = NamespaceCache.find(NSDecl);
5053
259k
  if (I != NamespaceCache.end())
5054
225k
    return cast<llvm::DINamespace>(I->second);
5055
5056
33.9k
  llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
5057
  // Don't trust the context if it is a DIModule (see comment above).
5058
33.9k
  llvm::DINamespace *NS =
5059
33.9k
      DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
5060
33.9k
  NamespaceCache[NSDecl].reset(NS);
5061
33.9k
  return NS;
5062
259k
}
5063
5064
249
void CGDebugInfo::setDwoId(uint64_t Signature) {
5065
249
  assert(TheCU && "no main compile unit");
5066
0
  TheCU->setDWOId(Signature);
5067
249
}
5068
5069
10.4k
void CGDebugInfo::finalize() {
5070
  // Creating types might create further types - invalidating the current
5071
  // element and the size(), so don't cache/reference them.
5072
13.3k
  for (size_t i = 0; i != ObjCInterfaceCache.size(); 
++i2.92k
) {
5073
2.92k
    ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
5074
2.92k
    llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
5075
2.92k
                           ? 
CreateTypeDefinition(E.Type, E.Unit)2.73k
5076
2.92k
                           : 
E.Decl191
;
5077
2.92k
    DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
5078
2.92k
  }
5079
5080
  // Add methods to interface.
5081
10.4k
  for (const auto &P : ObjCMethodCache) {
5082
8
    if (P.second.empty())
5083
0
      continue;
5084
5085
8
    QualType QTy(P.first->getTypeForDecl(), 0);
5086
8
    auto It = TypeCache.find(QTy.getAsOpaquePtr());
5087
8
    assert(It != TypeCache.end());
5088
5089
0
    llvm::DICompositeType *InterfaceDecl =
5090
8
        cast<llvm::DICompositeType>(It->second);
5091
5092
8
    auto CurElts = InterfaceDecl->getElements();
5093
8
    SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
5094
5095
    // For DWARF v4 or earlier, only add objc_direct methods.
5096
8
    for (auto &SubprogramDirect : P.second)
5097
31
      if (CGM.getCodeGenOpts().DwarfVersion >= 5 || 
SubprogramDirect.getInt()22
)
5098
31
        EltTys.push_back(SubprogramDirect.getPointer());
5099
5100
8
    llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5101
8
    DBuilder.replaceArrays(InterfaceDecl, Elements);
5102
8
  }
5103
5104
15.9k
  for (const auto &P : ReplaceMap) {
5105
15.9k
    assert(P.second);
5106
0
    auto *Ty = cast<llvm::DIType>(P.second);