Coverage Report

Created: 2022-05-17 06:19

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