Coverage Report

Created: 2020-10-24 06:27

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