Coverage Report

Created: 2022-07-16 07:03

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