1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This coordinates the debug information generation while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/VTableBuilder.h"
31 #include "clang/Basic/CodeGenOptions.h"
32 #include "clang/Basic/FileManager.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/Version.h"
35 #include "clang/Frontend/FrontendOptions.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/ModuleMap.h"
38 #include "clang/Lex/PreprocessorOptions.h"
39 #include "llvm/ADT/DenseSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/MD5.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/SHA1.h"
53 #include "llvm/Support/SHA256.h"
54 #include "llvm/Support/TimeProfiler.h"
56 using namespace clang
;
57 using namespace clang::CodeGen
;
59 static uint32_t getTypeAlignIfRequired(const Type
*Ty
, const ASTContext
&Ctx
) {
60 auto TI
= Ctx
.getTypeInfo(Ty
);
61 return TI
.isAlignRequired() ? TI
.Align
: 0;
64 static uint32_t getTypeAlignIfRequired(QualType Ty
, const ASTContext
&Ctx
) {
65 return getTypeAlignIfRequired(Ty
.getTypePtr(), Ctx
);
68 static uint32_t getDeclAlignIfRequired(const Decl
*D
, const ASTContext
&Ctx
) {
69 return D
->hasAttr
<AlignedAttr
>() ? D
->getMaxAlignment() : 0;
72 CGDebugInfo::CGDebugInfo(CodeGenModule
&CGM
)
73 : CGM(CGM
), DebugKind(CGM
.getCodeGenOpts().getDebugInfo()),
74 DebugTypeExtRefs(CGM
.getCodeGenOpts().DebugTypeExtRefs
),
75 DBuilder(CGM
.getModule()) {
79 CGDebugInfo::~CGDebugInfo() {
80 assert(LexicalBlockStack
.empty() &&
81 "Region stack mismatch, stack not empty!");
84 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
,
85 SourceLocation TemporaryLocation
)
87 init(TemporaryLocation
);
90 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
,
92 SourceLocation TemporaryLocation
)
94 init(TemporaryLocation
, DefaultToEmpty
);
97 void ApplyDebugLocation::init(SourceLocation TemporaryLocation
,
98 bool DefaultToEmpty
) {
99 auto *DI
= CGF
->getDebugInfo();
105 OriginalLocation
= CGF
->Builder
.getCurrentDebugLocation();
107 if (OriginalLocation
&& !DI
->CGM
.getExpressionLocationsEnabled())
110 if (TemporaryLocation
.isValid()) {
111 DI
->EmitLocation(CGF
->Builder
, TemporaryLocation
);
115 if (DefaultToEmpty
) {
116 CGF
->Builder
.SetCurrentDebugLocation(llvm::DebugLoc());
120 // Construct a location that has a valid scope, but no line info.
121 assert(!DI
->LexicalBlockStack
.empty());
122 CGF
->Builder
.SetCurrentDebugLocation(
123 llvm::DILocation::get(DI
->LexicalBlockStack
.back()->getContext(), 0, 0,
124 DI
->LexicalBlockStack
.back(), DI
->getInlinedAt()));
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
, const Expr
*E
)
129 init(E
->getExprLoc());
132 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
, llvm::DebugLoc Loc
)
134 if (!CGF
.getDebugInfo()) {
138 OriginalLocation
= CGF
.Builder
.getCurrentDebugLocation();
140 CGF
.Builder
.SetCurrentDebugLocation(std::move(Loc
));
143 ApplyDebugLocation::~ApplyDebugLocation() {
144 // Query CGF so the location isn't overwritten when location updates are
145 // temporarily disabled (for C++ default function arguments)
147 CGF
->Builder
.SetCurrentDebugLocation(std::move(OriginalLocation
));
150 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction
&CGF
,
151 GlobalDecl InlinedFn
)
153 if (!CGF
.getDebugInfo()) {
157 auto &DI
= *CGF
.getDebugInfo();
158 SavedLocation
= DI
.getLocation();
159 assert((DI
.getInlinedAt() ==
160 CGF
.Builder
.getCurrentDebugLocation()->getInlinedAt()) &&
161 "CGDebugInfo and IRBuilder are out of sync");
163 DI
.EmitInlineFunctionStart(CGF
.Builder
, InlinedFn
);
166 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
169 auto &DI
= *CGF
->getDebugInfo();
170 DI
.EmitInlineFunctionEnd(CGF
->Builder
);
171 DI
.EmitLocation(CGF
->Builder
, SavedLocation
);
174 void CGDebugInfo::setLocation(SourceLocation Loc
) {
175 // If the new location isn't valid return.
179 CurLoc
= CGM
.getContext().getSourceManager().getExpansionLoc(Loc
);
181 // If we've changed files in the middle of a lexical scope go ahead
182 // and create a new lexical scope with file node if it's different
183 // from the one in the scope.
184 if (LexicalBlockStack
.empty())
187 SourceManager
&SM
= CGM
.getContext().getSourceManager();
188 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
189 PresumedLoc PCLoc
= SM
.getPresumedLoc(CurLoc
);
190 if (PCLoc
.isInvalid() || Scope
->getFile() == getOrCreateFile(CurLoc
))
193 if (auto *LBF
= dyn_cast
<llvm::DILexicalBlockFile
>(Scope
)) {
194 LexicalBlockStack
.pop_back();
195 LexicalBlockStack
.emplace_back(DBuilder
.createLexicalBlockFile(
196 LBF
->getScope(), getOrCreateFile(CurLoc
)));
197 } else if (isa
<llvm::DILexicalBlock
>(Scope
) ||
198 isa
<llvm::DISubprogram
>(Scope
)) {
199 LexicalBlockStack
.pop_back();
200 LexicalBlockStack
.emplace_back(
201 DBuilder
.createLexicalBlockFile(Scope
, getOrCreateFile(CurLoc
)));
205 llvm::DIScope
*CGDebugInfo::getDeclContextDescriptor(const Decl
*D
) {
206 llvm::DIScope
*Mod
= getParentModuleOrNull(D
);
207 return getContextDescriptor(cast
<Decl
>(D
->getDeclContext()),
211 llvm::DIScope
*CGDebugInfo::getContextDescriptor(const Decl
*Context
,
212 llvm::DIScope
*Default
) {
216 auto I
= RegionMap
.find(Context
);
217 if (I
!= RegionMap
.end()) {
218 llvm::Metadata
*V
= I
->second
;
219 return dyn_cast_or_null
<llvm::DIScope
>(V
);
223 if (const auto *NSDecl
= dyn_cast
<NamespaceDecl
>(Context
))
224 return getOrCreateNamespace(NSDecl
);
226 if (const auto *RDecl
= dyn_cast
<RecordDecl
>(Context
))
227 if (!RDecl
->isDependentType())
228 return getOrCreateType(CGM
.getContext().getTypeDeclType(RDecl
),
233 PrintingPolicy
CGDebugInfo::getPrintingPolicy() const {
234 PrintingPolicy PP
= CGM
.getContext().getPrintingPolicy();
236 // If we're emitting codeview, it's important to try to match MSVC's naming so
237 // that visualizers written for MSVC will trigger for our class names. In
238 // particular, we can't have spaces between arguments of standard templates
239 // like basic_string and vector, but we must have spaces between consecutive
240 // angle brackets that close nested template argument lists.
241 if (CGM
.getCodeGenOpts().EmitCodeView
) {
242 PP
.MSVCFormatting
= true;
243 PP
.SplitTemplateClosers
= true;
245 // For DWARF, printing rules are underspecified.
246 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
247 PP
.SplitTemplateClosers
= true;
250 PP
.SuppressInlineNamespace
= false;
251 PP
.PrintCanonicalTypes
= true;
252 PP
.UsePreferredNames
= false;
253 PP
.AlwaysIncludeTypeForTemplateArgument
= true;
254 PP
.UseEnumerators
= false;
256 // Apply -fdebug-prefix-map.
257 PP
.Callbacks
= &PrintCB
;
261 StringRef
CGDebugInfo::getFunctionName(const FunctionDecl
*FD
) {
262 return internString(GetName(FD
));
265 StringRef
CGDebugInfo::getObjCMethodName(const ObjCMethodDecl
*OMD
) {
266 SmallString
<256> MethodName
;
267 llvm::raw_svector_ostream
OS(MethodName
);
268 OS
<< (OMD
->isInstanceMethod() ? '-' : '+') << '[';
269 const DeclContext
*DC
= OMD
->getDeclContext();
270 if (const auto *OID
= dyn_cast
<ObjCImplementationDecl
>(DC
)) {
271 OS
<< OID
->getName();
272 } else if (const auto *OID
= dyn_cast
<ObjCInterfaceDecl
>(DC
)) {
273 OS
<< OID
->getName();
274 } else if (const auto *OC
= dyn_cast
<ObjCCategoryDecl
>(DC
)) {
275 if (OC
->IsClassExtension()) {
276 OS
<< OC
->getClassInterface()->getName();
278 OS
<< OC
->getIdentifier()->getNameStart() << '('
279 << OC
->getIdentifier()->getNameStart() << ')';
281 } else if (const auto *OCD
= dyn_cast
<ObjCCategoryImplDecl
>(DC
)) {
282 OS
<< OCD
->getClassInterface()->getName() << '(' << OCD
->getName() << ')';
284 OS
<< ' ' << OMD
->getSelector().getAsString() << ']';
286 return internString(OS
.str());
289 StringRef
CGDebugInfo::getSelectorName(Selector S
) {
290 return internString(S
.getAsString());
293 StringRef
CGDebugInfo::getClassName(const RecordDecl
*RD
) {
294 if (isa
<ClassTemplateSpecializationDecl
>(RD
)) {
295 // Copy this name on the side and use its reference.
296 return internString(GetName(RD
));
299 // quick optimization to avoid having to intern strings that are already
300 // stored reliably elsewhere
301 if (const IdentifierInfo
*II
= RD
->getIdentifier())
302 return II
->getName();
304 // The CodeView printer in LLVM wants to see the names of unnamed types
305 // because they need to have a unique identifier.
306 // These names are used to reconstruct the fully qualified type names.
307 if (CGM
.getCodeGenOpts().EmitCodeView
) {
308 if (const TypedefNameDecl
*D
= RD
->getTypedefNameForAnonDecl()) {
309 assert(RD
->getDeclContext() == D
->getDeclContext() &&
310 "Typedef should not be in another decl context!");
311 assert(D
->getDeclName().getAsIdentifierInfo() &&
312 "Typedef was not named!");
313 return D
->getDeclName().getAsIdentifierInfo()->getName();
316 if (CGM
.getLangOpts().CPlusPlus
) {
319 ASTContext
&Context
= CGM
.getContext();
320 if (const DeclaratorDecl
*DD
= Context
.getDeclaratorForUnnamedTagDecl(RD
))
321 // Anonymous types without a name for linkage purposes have their
322 // declarator mangled in if they have one.
323 Name
= DD
->getName();
324 else if (const TypedefNameDecl
*TND
=
325 Context
.getTypedefNameForUnnamedTagDecl(RD
))
326 // Anonymous types without a name for linkage purposes have their
327 // associate typedef mangled in if they have one.
328 Name
= TND
->getName();
330 // Give lambdas a display name based on their name mangling.
331 if (const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
332 if (CXXRD
->isLambda())
334 CGM
.getCXXABI().getMangleContext().getLambdaString(CXXRD
));
337 SmallString
<256> UnnamedType("<unnamed-type-");
340 return internString(UnnamedType
);
348 std::optional
<llvm::DIFile::ChecksumKind
>
349 CGDebugInfo::computeChecksum(FileID FID
, SmallString
<64> &Checksum
) const {
352 if (!CGM
.getCodeGenOpts().EmitCodeView
&&
353 CGM
.getCodeGenOpts().DwarfVersion
< 5)
356 SourceManager
&SM
= CGM
.getContext().getSourceManager();
357 std::optional
<llvm::MemoryBufferRef
> MemBuffer
= SM
.getBufferOrNone(FID
);
361 auto Data
= llvm::arrayRefFromStringRef(MemBuffer
->getBuffer());
362 switch (CGM
.getCodeGenOpts().getDebugSrcHash()) {
363 case clang::CodeGenOptions::DSH_MD5
:
364 llvm::toHex(llvm::MD5::hash(Data
), /*LowerCase=*/true, Checksum
);
365 return llvm::DIFile::CSK_MD5
;
366 case clang::CodeGenOptions::DSH_SHA1
:
367 llvm::toHex(llvm::SHA1::hash(Data
), /*LowerCase=*/true, Checksum
);
368 return llvm::DIFile::CSK_SHA1
;
369 case clang::CodeGenOptions::DSH_SHA256
:
370 llvm::toHex(llvm::SHA256::hash(Data
), /*LowerCase=*/true, Checksum
);
371 return llvm::DIFile::CSK_SHA256
;
373 llvm_unreachable("Unhandled DebugSrcHashKind enum");
376 std::optional
<StringRef
> CGDebugInfo::getSource(const SourceManager
&SM
,
378 if (!CGM
.getCodeGenOpts().EmbedSource
)
381 bool SourceInvalid
= false;
382 StringRef Source
= SM
.getBufferData(FID
, &SourceInvalid
);
390 llvm::DIFile
*CGDebugInfo::getOrCreateFile(SourceLocation Loc
) {
391 SourceManager
&SM
= CGM
.getContext().getSourceManager();
394 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
;
396 if (Loc
.isInvalid()) {
397 // The DIFile used by the CU is distinct from the main source file. Call
398 // createFile() below for canonicalization if the source file was specified
399 // with an absolute path.
400 FileName
= TheCU
->getFile()->getFilename();
401 CSInfo
= TheCU
->getFile()->getChecksum();
403 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
);
404 FileName
= PLoc
.getFilename();
406 if (FileName
.empty()) {
407 FileName
= TheCU
->getFile()->getFilename();
409 FileName
= PLoc
.getFilename();
411 FID
= PLoc
.getFileID();
414 // Cache the results.
415 auto It
= DIFileCache
.find(FileName
.data());
416 if (It
!= DIFileCache
.end()) {
417 // Verify that the information still exists.
418 if (llvm::Metadata
*V
= It
->second
)
419 return cast
<llvm::DIFile
>(V
);
422 // Put Checksum at a scope where it will persist past the createFile call.
423 SmallString
<64> Checksum
;
425 std::optional
<llvm::DIFile::ChecksumKind
> CSKind
=
426 computeChecksum(FID
, Checksum
);
428 CSInfo
.emplace(*CSKind
, Checksum
);
430 return createFile(FileName
, CSInfo
, getSource(SM
, SM
.getFileID(Loc
)));
433 llvm::DIFile
*CGDebugInfo::createFile(
435 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
,
436 std::optional
<StringRef
> Source
) {
439 std::string RemappedFile
= remapDIPath(FileName
);
440 std::string CurDir
= remapDIPath(getCurrentDirname());
441 SmallString
<128> DirBuf
;
442 SmallString
<128> FileBuf
;
443 if (llvm::sys::path::is_absolute(RemappedFile
)) {
444 // Strip the common prefix (if it is more than just "/" or "C:\") from
445 // current directory and FileName for a more space-efficient encoding.
446 auto FileIt
= llvm::sys::path::begin(RemappedFile
);
447 auto FileE
= llvm::sys::path::end(RemappedFile
);
448 auto CurDirIt
= llvm::sys::path::begin(CurDir
);
449 auto CurDirE
= llvm::sys::path::end(CurDir
);
450 for (; CurDirIt
!= CurDirE
&& *CurDirIt
== *FileIt
; ++CurDirIt
, ++FileIt
)
451 llvm::sys::path::append(DirBuf
, *CurDirIt
);
452 if (llvm::sys::path::root_path(DirBuf
) == DirBuf
) {
453 // Don't strip the common prefix if it is only the root ("/" or "C:\")
454 // since that would make LLVM diagnostic locations confusing.
458 for (; FileIt
!= FileE
; ++FileIt
)
459 llvm::sys::path::append(FileBuf
, *FileIt
);
464 if (!llvm::sys::path::is_absolute(FileName
))
468 llvm::DIFile
*F
= DBuilder
.createFile(File
, Dir
, CSInfo
, Source
);
469 DIFileCache
[FileName
.data()].reset(F
);
473 std::string
CGDebugInfo::remapDIPath(StringRef Path
) const {
474 SmallString
<256> P
= Path
;
475 for (auto &[From
, To
] : llvm::reverse(CGM
.getCodeGenOpts().DebugPrefixMap
))
476 if (llvm::sys::path::replace_path_prefix(P
, From
, To
))
478 return P
.str().str();
481 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc
) {
484 SourceManager
&SM
= CGM
.getContext().getSourceManager();
485 return SM
.getPresumedLoc(Loc
).getLine();
488 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc
, bool Force
) {
489 // We may not want column information at all.
490 if (!Force
&& !CGM
.getCodeGenOpts().DebugColumnInfo
)
493 // If the location is invalid then use the current column.
494 if (Loc
.isInvalid() && CurLoc
.isInvalid())
496 SourceManager
&SM
= CGM
.getContext().getSourceManager();
497 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
.isValid() ? Loc
: CurLoc
);
498 return PLoc
.isValid() ? PLoc
.getColumn() : 0;
501 StringRef
CGDebugInfo::getCurrentDirname() {
502 if (!CGM
.getCodeGenOpts().DebugCompilationDir
.empty())
503 return CGM
.getCodeGenOpts().DebugCompilationDir
;
505 if (!CWDName
.empty())
507 llvm::ErrorOr
<std::string
> CWD
=
508 CGM
.getFileSystem()->getCurrentWorkingDirectory();
511 return CWDName
= internString(*CWD
);
514 void CGDebugInfo::CreateCompileUnit() {
515 SmallString
<64> Checksum
;
516 std::optional
<llvm::DIFile::ChecksumKind
> CSKind
;
517 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
;
519 // Should we be asking the SourceManager for the main file name, instead of
520 // accepting it as an argument? This just causes the main file name to
521 // mismatch with source locations and create extra lexical scopes or
522 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
523 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
524 // because that's what the SourceManager says)
526 // Get absolute path name.
527 SourceManager
&SM
= CGM
.getContext().getSourceManager();
528 auto &CGO
= CGM
.getCodeGenOpts();
529 const LangOptions
&LO
= CGM
.getLangOpts();
530 std::string MainFileName
= CGO
.MainFileName
;
531 if (MainFileName
.empty())
532 MainFileName
= "<stdin>";
534 // The main file name provided via the "-main-file-name" option contains just
535 // the file name itself with no path information. This file name may have had
536 // a relative path, so we look into the actual file entry for the main
537 // file to determine the real absolute path for the file.
538 std::string MainFileDir
;
539 if (OptionalFileEntryRef MainFile
=
540 SM
.getFileEntryRefForID(SM
.getMainFileID())) {
541 MainFileDir
= std::string(MainFile
->getDir().getName());
542 if (!llvm::sys::path::is_absolute(MainFileName
)) {
543 llvm::SmallString
<1024> MainFileDirSS(MainFileDir
);
544 llvm::sys::path::Style Style
=
545 LO
.UseTargetPathSeparator
546 ? (CGM
.getTarget().getTriple().isOSWindows()
547 ? llvm::sys::path::Style::windows_backslash
548 : llvm::sys::path::Style::posix
)
549 : llvm::sys::path::Style::native
;
550 llvm::sys::path::append(MainFileDirSS
, Style
, MainFileName
);
551 MainFileName
= std::string(
552 llvm::sys::path::remove_leading_dotslash(MainFileDirSS
, Style
));
554 // If the main file name provided is identical to the input file name, and
555 // if the input file is a preprocessed source, use the module name for
556 // debug info. The module name comes from the name specified in the first
557 // linemarker if the input is a preprocessed source.
558 if (MainFile
->getName() == MainFileName
&&
559 FrontendOptions::getInputKindForExtension(
560 MainFile
->getName().rsplit('.').second
)
562 MainFileName
= CGM
.getModule().getName().str();
564 CSKind
= computeChecksum(SM
.getMainFileID(), Checksum
);
567 llvm::dwarf::SourceLanguage LangTag
;
570 LangTag
= llvm::dwarf::DW_LANG_ObjC_plus_plus
;
571 else if (CGO
.DebugStrictDwarf
&& CGO
.DwarfVersion
< 5)
572 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus
;
573 else if (LO
.CPlusPlus14
)
574 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus_14
;
575 else if (LO
.CPlusPlus11
)
576 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus_11
;
578 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus
;
579 } else if (LO
.ObjC
) {
580 LangTag
= llvm::dwarf::DW_LANG_ObjC
;
581 } else if (LO
.OpenCL
&& (!CGM
.getCodeGenOpts().DebugStrictDwarf
||
582 CGM
.getCodeGenOpts().DwarfVersion
>= 5)) {
583 LangTag
= llvm::dwarf::DW_LANG_OpenCL
;
584 } else if (LO
.RenderScript
) {
585 LangTag
= llvm::dwarf::DW_LANG_GOOGLE_RenderScript
;
586 } else if (LO
.C11
&& !(CGO
.DebugStrictDwarf
&& CGO
.DwarfVersion
< 5)) {
587 LangTag
= llvm::dwarf::DW_LANG_C11
;
589 LangTag
= llvm::dwarf::DW_LANG_C99
;
591 LangTag
= llvm::dwarf::DW_LANG_C89
;
594 std::string Producer
= getClangFullVersion();
596 // Figure out which version of the ObjC runtime we have.
597 unsigned RuntimeVers
= 0;
599 RuntimeVers
= LO
.ObjCRuntime
.isNonFragile() ? 2 : 1;
601 llvm::DICompileUnit::DebugEmissionKind EmissionKind
;
603 case llvm::codegenoptions::NoDebugInfo
:
604 case llvm::codegenoptions::LocTrackingOnly
:
605 EmissionKind
= llvm::DICompileUnit::NoDebug
;
607 case llvm::codegenoptions::DebugLineTablesOnly
:
608 EmissionKind
= llvm::DICompileUnit::LineTablesOnly
;
610 case llvm::codegenoptions::DebugDirectivesOnly
:
611 EmissionKind
= llvm::DICompileUnit::DebugDirectivesOnly
;
613 case llvm::codegenoptions::DebugInfoConstructor
:
614 case llvm::codegenoptions::LimitedDebugInfo
:
615 case llvm::codegenoptions::FullDebugInfo
:
616 case llvm::codegenoptions::UnusedTypeInfo
:
617 EmissionKind
= llvm::DICompileUnit::FullDebug
;
622 auto &CGOpts
= CGM
.getCodeGenOpts();
623 // The DIFile used by the CU is distinct from the main source
624 // file. Its directory part specifies what becomes the
625 // DW_AT_comp_dir (the compilation directory), even if the source
626 // file was specified with an absolute path.
628 CSInfo
.emplace(*CSKind
, Checksum
);
629 llvm::DIFile
*CUFile
= DBuilder
.createFile(
630 remapDIPath(MainFileName
), remapDIPath(getCurrentDirname()), CSInfo
,
631 getSource(SM
, SM
.getMainFileID()));
633 StringRef Sysroot
, SDK
;
634 if (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
) {
635 Sysroot
= CGM
.getHeaderSearchOpts().Sysroot
;
636 auto B
= llvm::sys::path::rbegin(Sysroot
);
637 auto E
= llvm::sys::path::rend(Sysroot
);
638 auto It
= std::find_if(B
, E
, [](auto SDK
) { return SDK
.endswith(".sdk"); });
643 llvm::DICompileUnit::DebugNameTableKind NameTableKind
=
644 static_cast<llvm::DICompileUnit::DebugNameTableKind
>(
645 CGOpts
.DebugNameTable
);
646 if (CGM
.getTarget().getTriple().isNVPTX())
647 NameTableKind
= llvm::DICompileUnit::DebugNameTableKind::None
;
648 else if (CGM
.getTarget().getTriple().getVendor() == llvm::Triple::Apple
)
649 NameTableKind
= llvm::DICompileUnit::DebugNameTableKind::Apple
;
651 // Create new compile unit.
652 TheCU
= DBuilder
.createCompileUnit(
653 LangTag
, CUFile
, CGOpts
.EmitVersionIdentMetadata
? Producer
: "",
654 LO
.Optimize
|| CGOpts
.PrepareForLTO
|| CGOpts
.PrepareForThinLTO
,
655 CGOpts
.DwarfDebugFlags
, RuntimeVers
, CGOpts
.SplitDwarfFile
, EmissionKind
,
656 DwoId
, CGOpts
.SplitDwarfInlining
, CGOpts
.DebugInfoForProfiling
,
657 NameTableKind
, CGOpts
.DebugRangesBaseAddress
, remapDIPath(Sysroot
), SDK
);
660 llvm::DIType
*CGDebugInfo::CreateType(const BuiltinType
*BT
) {
661 llvm::dwarf::TypeKind Encoding
;
663 switch (BT
->getKind()) {
664 #define BUILTIN_TYPE(Id, SingletonId)
665 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
666 #include "clang/AST/BuiltinTypes.def"
667 case BuiltinType::Dependent
:
668 llvm_unreachable("Unexpected builtin type");
669 case BuiltinType::NullPtr
:
670 return DBuilder
.createNullPtrType();
671 case BuiltinType::Void
:
673 case BuiltinType::ObjCClass
:
676 DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
677 "objc_class", TheCU
, TheCU
->getFile(), 0);
679 case BuiltinType::ObjCId
: {
680 // typedef struct objc_class *Class;
681 // typedef struct objc_object {
690 DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
691 "objc_class", TheCU
, TheCU
->getFile(), 0);
693 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
695 auto *ISATy
= DBuilder
.createPointerType(ClassTy
, Size
);
697 ObjTy
= DBuilder
.createStructType(TheCU
, "objc_object", TheCU
->getFile(), 0,
698 0, 0, llvm::DINode::FlagZero
, nullptr,
699 llvm::DINodeArray());
701 DBuilder
.replaceArrays(
702 ObjTy
, DBuilder
.getOrCreateArray(&*DBuilder
.createMemberType(
703 ObjTy
, "isa", TheCU
->getFile(), 0, Size
, 0, 0,
704 llvm::DINode::FlagZero
, ISATy
)));
707 case BuiltinType::ObjCSel
: {
709 SelTy
= DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
710 "objc_selector", TheCU
,
711 TheCU
->getFile(), 0);
715 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
716 case BuiltinType::Id: \
717 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
719 #include "clang/Basic/OpenCLImageTypes.def"
720 case BuiltinType::OCLSampler
:
721 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy
);
722 case BuiltinType::OCLEvent
:
723 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy
);
724 case BuiltinType::OCLClkEvent
:
725 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy
);
726 case BuiltinType::OCLQueue
:
727 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy
);
728 case BuiltinType::OCLReserveID
:
729 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy
);
730 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
731 case BuiltinType::Id: \
732 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
733 #include "clang/Basic/OpenCLExtensionTypes.def"
735 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
736 #include "clang/Basic/AArch64SVEACLETypes.def"
738 ASTContext::BuiltinVectorTypeInfo Info
=
739 // For svcount_t, only the lower 2 bytes are relevant.
740 BT
->getKind() == BuiltinType::SveCount
741 ? ASTContext::BuiltinVectorTypeInfo(
742 CGM
.getContext().BoolTy
, llvm::ElementCount::getFixed(16),
744 : CGM
.getContext().getBuiltinVectorTypeInfo(BT
);
746 // A single vector of bytes may not suffice as the representation of
747 // svcount_t tuples because of the gap between the active 16bits of
748 // successive tuple members. Currently no such tuples are defined for
749 // svcount_t, so assert that NumVectors is 1.
750 assert((BT
->getKind() != BuiltinType::SveCount
|| Info
.NumVectors
== 1) &&
751 "Unsupported number of vectors for svcount_t");
753 // Debuggers can't extract 1bit from a vector, so will display a
754 // bitpattern for predicates instead.
755 unsigned NumElems
= Info
.EC
.getKnownMinValue() * Info
.NumVectors
;
756 if (Info
.ElementType
== CGM
.getContext().BoolTy
) {
758 Info
.ElementType
= CGM
.getContext().UnsignedCharTy
;
761 llvm::Metadata
*LowerBound
, *UpperBound
;
762 LowerBound
= llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
763 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), 0));
764 if (Info
.EC
.isScalable()) {
765 unsigned NumElemsPerVG
= NumElems
/ 2;
766 SmallVector
<uint64_t, 9> Expr(
767 {llvm::dwarf::DW_OP_constu
, NumElemsPerVG
, llvm::dwarf::DW_OP_bregx
,
768 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul
,
769 llvm::dwarf::DW_OP_constu
, 1, llvm::dwarf::DW_OP_minus
});
770 UpperBound
= DBuilder
.createExpression(Expr
);
772 UpperBound
= llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
773 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), NumElems
- 1));
775 llvm::Metadata
*Subscript
= DBuilder
.getOrCreateSubrange(
776 /*count*/ nullptr, LowerBound
, UpperBound
, /*stride*/ nullptr);
777 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
778 llvm::DIType
*ElemTy
=
779 getOrCreateType(Info
.ElementType
, TheCU
->getFile());
780 auto Align
= getTypeAlignIfRequired(BT
, CGM
.getContext());
781 return DBuilder
.createVectorType(/*Size*/ 0, Align
, ElemTy
,
784 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
785 // So we return a safe type here to avoid generating an error.
786 #define PPC_VECTOR_TYPE(Name, Id, size) \
787 case BuiltinType::Id:
788 #include "clang/Basic/PPCTypes.def"
789 return CreateType(cast
<const BuiltinType
>(CGM
.getContext().IntTy
));
791 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
792 #include "clang/Basic/RISCVVTypes.def"
794 ASTContext::BuiltinVectorTypeInfo Info
=
795 CGM
.getContext().getBuiltinVectorTypeInfo(BT
);
797 unsigned ElementCount
= Info
.EC
.getKnownMinValue();
798 unsigned SEW
= CGM
.getContext().getTypeSize(Info
.ElementType
);
800 bool Fractional
= false;
802 unsigned FixedSize
= ElementCount
* SEW
;
803 if (Info
.ElementType
== CGM
.getContext().BoolTy
) {
804 // Mask type only occupies one vector register.
806 } else if (FixedSize
< 64) {
807 // In RVV scalable vector types, we encode 64 bits in the fixed part.
809 LMUL
= 64 / FixedSize
;
811 LMUL
= FixedSize
/ 64;
814 // Element count = (VLENB / SEW) x LMUL
815 SmallVector
<uint64_t, 12> Expr(
816 // The DW_OP_bregx operation has two operands: a register which is
817 // specified by an unsigned LEB128 number, followed by a signed LEB128
819 {llvm::dwarf::DW_OP_bregx
, // Read the contents of a register.
820 4096 + 0xC22, // RISC-V VLENB CSR register.
821 0, // Offset for DW_OP_bregx. It is dummy here.
822 llvm::dwarf::DW_OP_constu
,
823 SEW
/ 8, // SEW is in bits.
824 llvm::dwarf::DW_OP_div
, llvm::dwarf::DW_OP_constu
, LMUL
});
826 Expr
.push_back(llvm::dwarf::DW_OP_div
);
828 Expr
.push_back(llvm::dwarf::DW_OP_mul
);
829 // Element max index = count - 1
830 Expr
.append({llvm::dwarf::DW_OP_constu
, 1, llvm::dwarf::DW_OP_minus
});
833 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
834 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), 0));
835 auto *UpperBound
= DBuilder
.createExpression(Expr
);
836 llvm::Metadata
*Subscript
= DBuilder
.getOrCreateSubrange(
837 /*count*/ nullptr, LowerBound
, UpperBound
, /*stride*/ nullptr);
838 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
839 llvm::DIType
*ElemTy
=
840 getOrCreateType(Info
.ElementType
, TheCU
->getFile());
842 auto Align
= getTypeAlignIfRequired(BT
, CGM
.getContext());
843 return DBuilder
.createVectorType(/*Size=*/0, Align
, ElemTy
,
847 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
848 case BuiltinType::Id: { \
851 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
852 MangledName, TheCU, TheCU->getFile(), 0); \
853 return SingletonId; \
855 #include "clang/Basic/WebAssemblyReferenceTypes.def"
857 case BuiltinType::UChar
:
858 case BuiltinType::Char_U
:
859 Encoding
= llvm::dwarf::DW_ATE_unsigned_char
;
861 case BuiltinType::Char_S
:
862 case BuiltinType::SChar
:
863 Encoding
= llvm::dwarf::DW_ATE_signed_char
;
865 case BuiltinType::Char8
:
866 case BuiltinType::Char16
:
867 case BuiltinType::Char32
:
868 Encoding
= llvm::dwarf::DW_ATE_UTF
;
870 case BuiltinType::UShort
:
871 case BuiltinType::UInt
:
872 case BuiltinType::UInt128
:
873 case BuiltinType::ULong
:
874 case BuiltinType::WChar_U
:
875 case BuiltinType::ULongLong
:
876 Encoding
= llvm::dwarf::DW_ATE_unsigned
;
878 case BuiltinType::Short
:
879 case BuiltinType::Int
:
880 case BuiltinType::Int128
:
881 case BuiltinType::Long
:
882 case BuiltinType::WChar_S
:
883 case BuiltinType::LongLong
:
884 Encoding
= llvm::dwarf::DW_ATE_signed
;
886 case BuiltinType::Bool
:
887 Encoding
= llvm::dwarf::DW_ATE_boolean
;
889 case BuiltinType::Half
:
890 case BuiltinType::Float
:
891 case BuiltinType::LongDouble
:
892 case BuiltinType::Float16
:
893 case BuiltinType::BFloat16
:
894 case BuiltinType::Float128
:
895 case BuiltinType::Double
:
896 case BuiltinType::Ibm128
:
897 // FIXME: For targets where long double, __ibm128 and __float128 have the
898 // same size, they are currently indistinguishable in the debugger without
899 // some special treatment. However, there is currently no consensus on
900 // encoding and this should be updated once a DWARF encoding exists for
901 // distinct floating point types of the same size.
902 Encoding
= llvm::dwarf::DW_ATE_float
;
904 case BuiltinType::ShortAccum
:
905 case BuiltinType::Accum
:
906 case BuiltinType::LongAccum
:
907 case BuiltinType::ShortFract
:
908 case BuiltinType::Fract
:
909 case BuiltinType::LongFract
:
910 case BuiltinType::SatShortFract
:
911 case BuiltinType::SatFract
:
912 case BuiltinType::SatLongFract
:
913 case BuiltinType::SatShortAccum
:
914 case BuiltinType::SatAccum
:
915 case BuiltinType::SatLongAccum
:
916 Encoding
= llvm::dwarf::DW_ATE_signed_fixed
;
918 case BuiltinType::UShortAccum
:
919 case BuiltinType::UAccum
:
920 case BuiltinType::ULongAccum
:
921 case BuiltinType::UShortFract
:
922 case BuiltinType::UFract
:
923 case BuiltinType::ULongFract
:
924 case BuiltinType::SatUShortAccum
:
925 case BuiltinType::SatUAccum
:
926 case BuiltinType::SatULongAccum
:
927 case BuiltinType::SatUShortFract
:
928 case BuiltinType::SatUFract
:
929 case BuiltinType::SatULongFract
:
930 Encoding
= llvm::dwarf::DW_ATE_unsigned_fixed
;
934 BTName
= BT
->getName(CGM
.getLangOpts());
935 // Bit size and offset of the type.
936 uint64_t Size
= CGM
.getContext().getTypeSize(BT
);
937 return DBuilder
.createBasicType(BTName
, Size
, Encoding
);
940 llvm::DIType
*CGDebugInfo::CreateType(const BitIntType
*Ty
) {
942 StringRef Name
= Ty
->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
943 llvm::dwarf::TypeKind Encoding
= Ty
->isUnsigned()
944 ? llvm::dwarf::DW_ATE_unsigned
945 : llvm::dwarf::DW_ATE_signed
;
947 return DBuilder
.createBasicType(Name
, CGM
.getContext().getTypeSize(Ty
),
951 llvm::DIType
*CGDebugInfo::CreateType(const ComplexType
*Ty
) {
952 // Bit size and offset of the type.
953 llvm::dwarf::TypeKind Encoding
= llvm::dwarf::DW_ATE_complex_float
;
954 if (Ty
->isComplexIntegerType())
955 Encoding
= llvm::dwarf::DW_ATE_lo_user
;
957 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
958 return DBuilder
.createBasicType("complex", Size
, Encoding
);
961 static void stripUnusedQualifiers(Qualifiers
&Q
) {
962 // Ignore these qualifiers for now.
963 Q
.removeObjCGCAttr();
964 Q
.removeAddressSpace();
965 Q
.removeObjCLifetime();
969 static llvm::dwarf::Tag
getNextQualifier(Qualifiers
&Q
) {
972 return llvm::dwarf::DW_TAG_const_type
;
974 if (Q
.hasVolatile()) {
976 return llvm::dwarf::DW_TAG_volatile_type
;
978 if (Q
.hasRestrict()) {
980 return llvm::dwarf::DW_TAG_restrict_type
;
982 return (llvm::dwarf::Tag
)0;
985 llvm::DIType
*CGDebugInfo::CreateQualifiedType(QualType Ty
,
986 llvm::DIFile
*Unit
) {
987 QualifierCollector Qc
;
988 const Type
*T
= Qc
.strip(Ty
);
990 stripUnusedQualifiers(Qc
);
992 // We will create one Derived type for one qualifier and recurse to handle any
994 llvm::dwarf::Tag Tag
= getNextQualifier(Qc
);
996 assert(Qc
.empty() && "Unknown type qualifier for debug info");
997 return getOrCreateType(QualType(T
, 0), Unit
);
1000 auto *FromTy
= getOrCreateType(Qc
.apply(CGM
.getContext(), T
), Unit
);
1002 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1003 // CVR derived types.
1004 return DBuilder
.createQualifiedType(Tag
, FromTy
);
1007 llvm::DIType
*CGDebugInfo::CreateQualifiedType(const FunctionProtoType
*F
,
1008 llvm::DIFile
*Unit
) {
1009 FunctionProtoType::ExtProtoInfo EPI
= F
->getExtProtoInfo();
1010 Qualifiers
&Q
= EPI
.TypeQuals
;
1011 stripUnusedQualifiers(Q
);
1013 // We will create one Derived type for one qualifier and recurse to handle any
1015 llvm::dwarf::Tag Tag
= getNextQualifier(Q
);
1017 assert(Q
.empty() && "Unknown type qualifier for debug info");
1022 getOrCreateType(CGM
.getContext().getFunctionType(F
->getReturnType(),
1023 F
->getParamTypes(), EPI
),
1026 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1027 // CVR derived types.
1028 return DBuilder
.createQualifiedType(Tag
, FromTy
);
1031 llvm::DIType
*CGDebugInfo::CreateType(const ObjCObjectPointerType
*Ty
,
1032 llvm::DIFile
*Unit
) {
1034 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1035 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1036 // debug info, we want to emit 'id' in both cases.
1037 if (Ty
->isObjCQualifiedIdType())
1038 return getOrCreateType(CGM
.getContext().getObjCIdType(), Unit
);
1040 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
1041 Ty
->getPointeeType(), Unit
);
1044 llvm::DIType
*CGDebugInfo::CreateType(const PointerType
*Ty
,
1045 llvm::DIFile
*Unit
) {
1046 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
1047 Ty
->getPointeeType(), Unit
);
1050 /// \return whether a C++ mangling exists for the type defined by TD.
1051 static bool hasCXXMangling(const TagDecl
*TD
, llvm::DICompileUnit
*TheCU
) {
1052 switch (TheCU
->getSourceLanguage()) {
1053 case llvm::dwarf::DW_LANG_C_plus_plus
:
1054 case llvm::dwarf::DW_LANG_C_plus_plus_11
:
1055 case llvm::dwarf::DW_LANG_C_plus_plus_14
:
1057 case llvm::dwarf::DW_LANG_ObjC_plus_plus
:
1058 return isa
<CXXRecordDecl
>(TD
) || isa
<EnumDecl
>(TD
);
1064 // Determines if the debug info for this tag declaration needs a type
1065 // identifier. The purpose of the unique identifier is to deduplicate type
1066 // information for identical types across TUs. Because of the C++ one definition
1067 // rule (ODR), it is valid to assume that the type is defined the same way in
1068 // every TU and its debug info is equivalent.
1070 // C does not have the ODR, and it is common for codebases to contain multiple
1071 // different definitions of a struct with the same name in different TUs.
1072 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1073 // identifer. Type information in C is smaller and simpler than C++ type
1074 // information, so the increase in debug info size is negligible.
1076 // If the type is not externally visible, it should be unique to the current TU,
1077 // and should not need an identifier to participate in type deduplication.
1078 // However, when emitting CodeView, the format internally uses these
1079 // unique type name identifers for references between debug info. For example,
1080 // the method of a class in an anonymous namespace uses the identifer to refer
1081 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1082 // for such types, so when emitting CodeView, always use identifiers for C++
1083 // types. This may create problems when attempting to emit CodeView when the MS
1084 // C++ ABI is not in use.
1085 static bool needsTypeIdentifier(const TagDecl
*TD
, CodeGenModule
&CGM
,
1086 llvm::DICompileUnit
*TheCU
) {
1087 // We only add a type identifier for types with C++ name mangling.
1088 if (!hasCXXMangling(TD
, TheCU
))
1091 // Externally visible types with C++ mangling need a type identifier.
1092 if (TD
->isExternallyVisible())
1095 // CodeView types with C++ mangling need a type identifier.
1096 if (CGM
.getCodeGenOpts().EmitCodeView
)
1102 // Returns a unique type identifier string if one exists, or an empty string.
1103 static SmallString
<256> getTypeIdentifier(const TagType
*Ty
, CodeGenModule
&CGM
,
1104 llvm::DICompileUnit
*TheCU
) {
1105 SmallString
<256> Identifier
;
1106 const TagDecl
*TD
= Ty
->getDecl();
1108 if (!needsTypeIdentifier(TD
, CGM
, TheCU
))
1110 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(TD
))
1111 if (RD
->getDefinition())
1112 if (RD
->isDynamicClass() &&
1113 CGM
.getVTableLinkage(RD
) == llvm::GlobalValue::ExternalLinkage
)
1116 // TODO: This is using the RTTI name. Is there a better way to get
1117 // a unique string for a type?
1118 llvm::raw_svector_ostream
Out(Identifier
);
1119 CGM
.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty
, 0), Out
);
1123 /// \return the appropriate DWARF tag for a composite type.
1124 static llvm::dwarf::Tag
getTagForRecord(const RecordDecl
*RD
) {
1125 llvm::dwarf::Tag Tag
;
1126 if (RD
->isStruct() || RD
->isInterface())
1127 Tag
= llvm::dwarf::DW_TAG_structure_type
;
1128 else if (RD
->isUnion())
1129 Tag
= llvm::dwarf::DW_TAG_union_type
;
1131 // FIXME: This could be a struct type giving a default visibility different
1132 // than C++ class type, but needs llvm metadata changes first.
1133 assert(RD
->isClass());
1134 Tag
= llvm::dwarf::DW_TAG_class_type
;
1139 llvm::DICompositeType
*
1140 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType
*Ty
,
1141 llvm::DIScope
*Ctx
) {
1142 const RecordDecl
*RD
= Ty
->getDecl();
1143 if (llvm::DIType
*T
= getTypeOrNull(CGM
.getContext().getRecordType(RD
)))
1144 return cast
<llvm::DICompositeType
>(T
);
1145 llvm::DIFile
*DefUnit
= getOrCreateFile(RD
->getLocation());
1146 const unsigned Line
=
1147 getLineNumber(RD
->getLocation().isValid() ? RD
->getLocation() : CurLoc
);
1148 StringRef RDName
= getClassName(RD
);
1153 const RecordDecl
*D
= RD
->getDefinition();
1154 if (D
&& D
->isCompleteDefinition())
1155 Size
= CGM
.getContext().getTypeSize(Ty
);
1157 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagFwdDecl
;
1159 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1160 // add the flag if a record has no definition because we don't know whether
1161 // it will be trivial or not.
1162 if (const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
1163 if (!CXXRD
->hasDefinition() ||
1164 (CXXRD
->hasDefinition() && !CXXRD
->isTrivial()))
1165 Flags
|= llvm::DINode::FlagNonTrivial
;
1168 SmallString
<256> Identifier
;
1169 // Don't include a linkage name in line tables only.
1170 if (CGM
.getCodeGenOpts().hasReducedDebugInfo())
1171 Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
1172 llvm::DICompositeType
*RetTy
= DBuilder
.createReplaceableCompositeType(
1173 getTagForRecord(RD
), RDName
, Ctx
, DefUnit
, Line
, 0, Size
, Align
, Flags
,
1175 if (CGM
.getCodeGenOpts().DebugFwdTemplateParams
)
1176 if (auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
1177 DBuilder
.replaceArrays(RetTy
, llvm::DINodeArray(),
1178 CollectCXXTemplateParams(TSpecial
, DefUnit
));
1179 ReplaceMap
.emplace_back(
1180 std::piecewise_construct
, std::make_tuple(Ty
),
1181 std::make_tuple(static_cast<llvm::Metadata
*>(RetTy
)));
1185 llvm::DIType
*CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag
,
1188 llvm::DIFile
*Unit
) {
1189 // Bit size, align and offset of the type.
1190 // Size is always the size of a pointer.
1191 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1192 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
1193 std::optional
<unsigned> DWARFAddressSpace
=
1194 CGM
.getTarget().getDWARFAddressSpace(
1195 CGM
.getTypes().getTargetAddressSpace(PointeeTy
));
1197 SmallVector
<llvm::Metadata
*, 4> Annots
;
1198 auto *BTFAttrTy
= dyn_cast
<BTFTagAttributedType
>(PointeeTy
);
1200 StringRef Tag
= BTFAttrTy
->getAttr()->getBTFTypeTag();
1202 llvm::Metadata
*Ops
[2] = {
1203 llvm::MDString::get(CGM
.getLLVMContext(), StringRef("btf_type_tag")),
1204 llvm::MDString::get(CGM
.getLLVMContext(), Tag
)};
1205 Annots
.insert(Annots
.begin(),
1206 llvm::MDNode::get(CGM
.getLLVMContext(), Ops
));
1208 BTFAttrTy
= dyn_cast
<BTFTagAttributedType
>(BTFAttrTy
->getWrappedType());
1211 llvm::DINodeArray Annotations
= nullptr;
1212 if (Annots
.size() > 0)
1213 Annotations
= DBuilder
.getOrCreateArray(Annots
);
1215 if (Tag
== llvm::dwarf::DW_TAG_reference_type
||
1216 Tag
== llvm::dwarf::DW_TAG_rvalue_reference_type
)
1217 return DBuilder
.createReferenceType(Tag
, getOrCreateType(PointeeTy
, Unit
),
1218 Size
, Align
, DWARFAddressSpace
);
1220 return DBuilder
.createPointerType(getOrCreateType(PointeeTy
, Unit
), Size
,
1221 Align
, DWARFAddressSpace
, StringRef(),
1225 llvm::DIType
*CGDebugInfo::getOrCreateStructPtrType(StringRef Name
,
1226 llvm::DIType
*&Cache
) {
1229 Cache
= DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
, Name
,
1230 TheCU
, TheCU
->getFile(), 0);
1231 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
1232 Cache
= DBuilder
.createPointerType(Cache
, Size
);
1236 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1237 const BlockPointerType
*Ty
, llvm::DIFile
*Unit
, llvm::DIDerivedType
*DescTy
,
1238 unsigned LineNo
, SmallVectorImpl
<llvm::Metadata
*> &EltTys
) {
1241 // Advanced by calls to CreateMemberType in increments of FType, then
1242 // returned as the overall size of the default elements.
1243 uint64_t FieldOffset
= 0;
1245 // Blocks in OpenCL have unique constraints which make the standard fields
1246 // redundant while requiring size and align fields for enqueue_kernel. See
1247 // initializeForBlockHeader in CGBlocks.cpp
1248 if (CGM
.getLangOpts().OpenCL
) {
1249 FType
= CGM
.getContext().IntTy
;
1250 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__size", &FieldOffset
));
1251 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__align", &FieldOffset
));
1253 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1254 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
1255 FType
= CGM
.getContext().IntTy
;
1256 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
1257 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__reserved", &FieldOffset
));
1258 FType
= CGM
.getContext().getPointerType(Ty
->getPointeeType());
1259 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__FuncPtr", &FieldOffset
));
1260 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1261 uint64_t FieldSize
= CGM
.getContext().getTypeSize(Ty
);
1262 uint32_t FieldAlign
= CGM
.getContext().getTypeAlign(Ty
);
1263 EltTys
.push_back(DBuilder
.createMemberType(
1264 Unit
, "__descriptor", nullptr, LineNo
, FieldSize
, FieldAlign
,
1265 FieldOffset
, llvm::DINode::FlagZero
, DescTy
));
1266 FieldOffset
+= FieldSize
;
1272 llvm::DIType
*CGDebugInfo::CreateType(const BlockPointerType
*Ty
,
1273 llvm::DIFile
*Unit
) {
1274 SmallVector
<llvm::Metadata
*, 8> EltTys
;
1276 uint64_t FieldOffset
;
1277 llvm::DINodeArray Elements
;
1280 FType
= CGM
.getContext().UnsignedLongTy
;
1281 EltTys
.push_back(CreateMemberType(Unit
, FType
, "reserved", &FieldOffset
));
1282 EltTys
.push_back(CreateMemberType(Unit
, FType
, "Size", &FieldOffset
));
1284 Elements
= DBuilder
.getOrCreateArray(EltTys
);
1287 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagAppleBlock
;
1290 DBuilder
.createStructType(Unit
, "__block_descriptor", nullptr, 0,
1291 FieldOffset
, 0, Flags
, nullptr, Elements
);
1293 // Bit size, align and offset of the type.
1294 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1296 auto *DescTy
= DBuilder
.createPointerType(EltTy
, Size
);
1298 FieldOffset
= collectDefaultElementTypesForBlockPointer(Ty
, Unit
, DescTy
,
1301 Elements
= DBuilder
.getOrCreateArray(EltTys
);
1303 // The __block_literal_generic structs are marked with a special
1304 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1305 // the debugger needs to know about. To allow type uniquing, emit
1306 // them without a name or a location.
1307 EltTy
= DBuilder
.createStructType(Unit
, "", nullptr, 0, FieldOffset
, 0,
1308 Flags
, nullptr, Elements
);
1310 return DBuilder
.createPointerType(EltTy
, Size
);
1313 llvm::DIType
*CGDebugInfo::CreateType(const TemplateSpecializationType
*Ty
,
1314 llvm::DIFile
*Unit
) {
1315 assert(Ty
->isTypeAlias());
1316 llvm::DIType
*Src
= getOrCreateType(Ty
->getAliasedType(), Unit
);
1318 const TemplateDecl
*TD
= Ty
->getTemplateName().getAsTemplateDecl();
1319 if (isa
<BuiltinTemplateDecl
>(TD
))
1322 const auto *AliasDecl
= cast
<TypeAliasTemplateDecl
>(TD
)->getTemplatedDecl();
1323 if (AliasDecl
->hasAttr
<NoDebugAttr
>())
1326 SmallString
<128> NS
;
1327 llvm::raw_svector_ostream
OS(NS
);
1329 auto PP
= getPrintingPolicy();
1330 Ty
->getTemplateName().print(OS
, PP
, TemplateName::Qualified::None
);
1332 // Disable PrintCanonicalTypes here because we want
1333 // the DW_AT_name to benefit from the TypePrinter's ability
1334 // to skip defaulted template arguments.
1336 // FIXME: Once -gsimple-template-names is enabled by default
1337 // and we attach template parameters to alias template DIEs
1338 // we don't need to worry about customizing the PrintingPolicy
1340 PP
.PrintCanonicalTypes
= false;
1341 printTemplateArgumentList(OS
, Ty
->template_arguments(), PP
,
1342 TD
->getTemplateParameters());
1344 SourceLocation Loc
= AliasDecl
->getLocation();
1345 return DBuilder
.createTypedef(Src
, OS
.str(), getOrCreateFile(Loc
),
1347 getDeclContextDescriptor(AliasDecl
));
1350 /// Convert an AccessSpecifier into the corresponding DINode flag.
1351 /// As an optimization, return 0 if the access specifier equals the
1352 /// default for the containing type.
1353 static llvm::DINode::DIFlags
getAccessFlag(AccessSpecifier Access
,
1354 const RecordDecl
*RD
) {
1355 AccessSpecifier Default
= clang::AS_none
;
1356 if (RD
&& RD
->isClass())
1357 Default
= clang::AS_private
;
1358 else if (RD
&& (RD
->isStruct() || RD
->isUnion()))
1359 Default
= clang::AS_public
;
1361 if (Access
== Default
)
1362 return llvm::DINode::FlagZero
;
1365 case clang::AS_private
:
1366 return llvm::DINode::FlagPrivate
;
1367 case clang::AS_protected
:
1368 return llvm::DINode::FlagProtected
;
1369 case clang::AS_public
:
1370 return llvm::DINode::FlagPublic
;
1371 case clang::AS_none
:
1372 return llvm::DINode::FlagZero
;
1374 llvm_unreachable("unexpected access enumerator");
1377 llvm::DIType
*CGDebugInfo::CreateType(const TypedefType
*Ty
,
1378 llvm::DIFile
*Unit
) {
1379 llvm::DIType
*Underlying
=
1380 getOrCreateType(Ty
->getDecl()->getUnderlyingType(), Unit
);
1382 if (Ty
->getDecl()->hasAttr
<NoDebugAttr
>())
1385 // We don't set size information, but do specify where the typedef was
1387 SourceLocation Loc
= Ty
->getDecl()->getLocation();
1389 uint32_t Align
= getDeclAlignIfRequired(Ty
->getDecl(), CGM
.getContext());
1390 // Typedefs are derived from some other type.
1391 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(Ty
->getDecl());
1393 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1394 const DeclContext
*DC
= Ty
->getDecl()->getDeclContext();
1395 if (isa
<RecordDecl
>(DC
))
1396 Flags
= getAccessFlag(Ty
->getDecl()->getAccess(), cast
<RecordDecl
>(DC
));
1398 return DBuilder
.createTypedef(Underlying
, Ty
->getDecl()->getName(),
1399 getOrCreateFile(Loc
), getLineNumber(Loc
),
1400 getDeclContextDescriptor(Ty
->getDecl()), Align
,
1401 Flags
, Annotations
);
1404 static unsigned getDwarfCC(CallingConv CC
) {
1407 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1411 return llvm::dwarf::DW_CC_BORLAND_stdcall
;
1412 case CC_X86FastCall
:
1413 return llvm::dwarf::DW_CC_BORLAND_msfastcall
;
1414 case CC_X86ThisCall
:
1415 return llvm::dwarf::DW_CC_BORLAND_thiscall
;
1416 case CC_X86VectorCall
:
1417 return llvm::dwarf::DW_CC_LLVM_vectorcall
;
1419 return llvm::dwarf::DW_CC_BORLAND_pascal
;
1421 return llvm::dwarf::DW_CC_LLVM_Win64
;
1423 return llvm::dwarf::DW_CC_LLVM_X86_64SysV
;
1425 case CC_AArch64VectorCall
:
1426 case CC_AArch64SVEPCS
:
1427 return llvm::dwarf::DW_CC_LLVM_AAPCS
;
1429 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP
;
1430 case CC_IntelOclBicc
:
1431 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc
;
1432 case CC_SpirFunction
:
1433 return llvm::dwarf::DW_CC_LLVM_SpirFunction
;
1434 case CC_OpenCLKernel
:
1435 case CC_AMDGPUKernelCall
:
1436 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel
;
1438 return llvm::dwarf::DW_CC_LLVM_Swift
;
1440 // [FIXME: swiftasynccc] Update to SwiftAsync once LLVM support lands.
1441 return llvm::dwarf::DW_CC_LLVM_Swift
;
1442 case CC_PreserveMost
:
1443 return llvm::dwarf::DW_CC_LLVM_PreserveMost
;
1444 case CC_PreserveAll
:
1445 return llvm::dwarf::DW_CC_LLVM_PreserveAll
;
1447 return llvm::dwarf::DW_CC_LLVM_X86RegCall
;
1449 return llvm::dwarf::DW_CC_LLVM_M68kRTD
;
1454 static llvm::DINode::DIFlags
getRefFlags(const FunctionProtoType
*Func
) {
1455 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1456 if (Func
->getExtProtoInfo().RefQualifier
== RQ_LValue
)
1457 Flags
|= llvm::DINode::FlagLValueReference
;
1458 if (Func
->getExtProtoInfo().RefQualifier
== RQ_RValue
)
1459 Flags
|= llvm::DINode::FlagRValueReference
;
1463 llvm::DIType
*CGDebugInfo::CreateType(const FunctionType
*Ty
,
1464 llvm::DIFile
*Unit
) {
1465 const auto *FPT
= dyn_cast
<FunctionProtoType
>(Ty
);
1467 if (llvm::DIType
*QTy
= CreateQualifiedType(FPT
, Unit
))
1471 // Create the type without any qualifiers
1473 SmallVector
<llvm::Metadata
*, 16> EltTys
;
1475 // Add the result type at least.
1476 EltTys
.push_back(getOrCreateType(Ty
->getReturnType(), Unit
));
1478 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1479 // Set up remainder of arguments if there is a prototype.
1480 // otherwise emit it as a variadic function.
1482 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
1484 Flags
= getRefFlags(FPT
);
1485 for (const QualType
&ParamType
: FPT
->param_types())
1486 EltTys
.push_back(getOrCreateType(ParamType
, Unit
));
1487 if (FPT
->isVariadic())
1488 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
1491 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(EltTys
);
1492 llvm::DIType
*F
= DBuilder
.createSubroutineType(
1493 EltTypeArray
, Flags
, getDwarfCC(Ty
->getCallConv()));
1497 llvm::DIDerivedType
*
1498 CGDebugInfo::createBitFieldType(const FieldDecl
*BitFieldDecl
,
1499 llvm::DIScope
*RecordTy
, const RecordDecl
*RD
) {
1500 StringRef Name
= BitFieldDecl
->getName();
1501 QualType Ty
= BitFieldDecl
->getType();
1502 if (BitFieldDecl
->hasAttr
<PreferredTypeAttr
>())
1503 Ty
= BitFieldDecl
->getAttr
<PreferredTypeAttr
>()->getType();
1504 SourceLocation Loc
= BitFieldDecl
->getLocation();
1505 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1506 llvm::DIType
*DebugType
= getOrCreateType(Ty
, VUnit
);
1508 // Get the location for the field.
1509 llvm::DIFile
*File
= getOrCreateFile(Loc
);
1510 unsigned Line
= getLineNumber(Loc
);
1512 const CGBitFieldInfo
&BitFieldInfo
=
1513 CGM
.getTypes().getCGRecordLayout(RD
).getBitFieldInfo(BitFieldDecl
);
1514 uint64_t SizeInBits
= BitFieldInfo
.Size
;
1515 assert(SizeInBits
> 0 && "found named 0-width bitfield");
1516 uint64_t StorageOffsetInBits
=
1517 CGM
.getContext().toBits(BitFieldInfo
.StorageOffset
);
1518 uint64_t Offset
= BitFieldInfo
.Offset
;
1519 // The bit offsets for big endian machines are reversed for big
1520 // endian target, compensate for that as the DIDerivedType requires
1521 // un-reversed offsets.
1522 if (CGM
.getDataLayout().isBigEndian())
1523 Offset
= BitFieldInfo
.StorageSize
- BitFieldInfo
.Size
- Offset
;
1524 uint64_t OffsetInBits
= StorageOffsetInBits
+ Offset
;
1525 llvm::DINode::DIFlags Flags
= getAccessFlag(BitFieldDecl
->getAccess(), RD
);
1526 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(BitFieldDecl
);
1527 return DBuilder
.createBitFieldMemberType(
1528 RecordTy
, Name
, File
, Line
, SizeInBits
, OffsetInBits
, StorageOffsetInBits
,
1529 Flags
, DebugType
, Annotations
);
1532 llvm::DIDerivedType
*CGDebugInfo::createBitFieldSeparatorIfNeeded(
1533 const FieldDecl
*BitFieldDecl
, const llvm::DIDerivedType
*BitFieldDI
,
1534 llvm::ArrayRef
<llvm::Metadata
*> PreviousFieldsDI
, const RecordDecl
*RD
) {
1536 if (!CGM
.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())
1540 Add a *single* zero-bitfield separator between two non-zero bitfields
1541 separated by one or more zero-bitfields. This is used to distinguish between
1542 structures such the ones below, where the memory layout is the same, but how
1543 the ABI assigns fields to registers differs.
1547 char a : 8; // on amdgpu, passed on v4
1554 char a : 8; // on amdgpu, passed on v4
1557 char x : 8; // passed on v5
1561 if (PreviousFieldsDI
.empty())
1564 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1565 auto *PreviousMDEntry
=
1566 PreviousFieldsDI
.empty() ? nullptr : PreviousFieldsDI
.back();
1567 auto *PreviousMDField
=
1568 dyn_cast_or_null
<llvm::DIDerivedType
>(PreviousMDEntry
);
1569 if (!PreviousMDField
|| !PreviousMDField
->isBitField() ||
1570 PreviousMDField
->getSizeInBits() == 0)
1573 auto PreviousBitfield
= RD
->field_begin();
1574 std::advance(PreviousBitfield
, BitFieldDecl
->getFieldIndex() - 1);
1576 assert(PreviousBitfield
->isBitField());
1578 ASTContext
&Context
= CGM
.getContext();
1579 if (!PreviousBitfield
->isZeroLengthBitField(Context
))
1582 QualType Ty
= PreviousBitfield
->getType();
1583 SourceLocation Loc
= PreviousBitfield
->getLocation();
1584 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1585 llvm::DIType
*DebugType
= getOrCreateType(Ty
, VUnit
);
1586 llvm::DIScope
*RecordTy
= BitFieldDI
->getScope();
1588 llvm::DIFile
*File
= getOrCreateFile(Loc
);
1589 unsigned Line
= getLineNumber(Loc
);
1591 uint64_t StorageOffsetInBits
=
1592 cast
<llvm::ConstantInt
>(BitFieldDI
->getStorageOffsetInBits())
1595 llvm::DINode::DIFlags Flags
=
1596 getAccessFlag(PreviousBitfield
->getAccess(), RD
);
1597 llvm::DINodeArray Annotations
=
1598 CollectBTFDeclTagAnnotations(*PreviousBitfield
);
1599 return DBuilder
.createBitFieldMemberType(
1600 RecordTy
, "", File
, Line
, 0, StorageOffsetInBits
, StorageOffsetInBits
,
1601 Flags
, DebugType
, Annotations
);
1604 llvm::DIType
*CGDebugInfo::createFieldType(
1605 StringRef name
, QualType type
, SourceLocation loc
, AccessSpecifier AS
,
1606 uint64_t offsetInBits
, uint32_t AlignInBits
, llvm::DIFile
*tunit
,
1607 llvm::DIScope
*scope
, const RecordDecl
*RD
, llvm::DINodeArray Annotations
) {
1608 llvm::DIType
*debugType
= getOrCreateType(type
, tunit
);
1610 // Get the location for the field.
1611 llvm::DIFile
*file
= getOrCreateFile(loc
);
1612 const unsigned line
= getLineNumber(loc
.isValid() ? loc
: CurLoc
);
1614 uint64_t SizeInBits
= 0;
1615 auto Align
= AlignInBits
;
1616 if (!type
->isIncompleteArrayType()) {
1617 TypeInfo TI
= CGM
.getContext().getTypeInfo(type
);
1618 SizeInBits
= TI
.Width
;
1620 Align
= getTypeAlignIfRequired(type
, CGM
.getContext());
1623 llvm::DINode::DIFlags flags
= getAccessFlag(AS
, RD
);
1624 return DBuilder
.createMemberType(scope
, name
, file
, line
, SizeInBits
, Align
,
1625 offsetInBits
, flags
, debugType
, Annotations
);
1628 void CGDebugInfo::CollectRecordLambdaFields(
1629 const CXXRecordDecl
*CXXDecl
, SmallVectorImpl
<llvm::Metadata
*> &elements
,
1630 llvm::DIType
*RecordTy
) {
1631 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1632 // has the name and the location of the variable so we should iterate over
1633 // both concurrently.
1634 const ASTRecordLayout
&layout
= CGM
.getContext().getASTRecordLayout(CXXDecl
);
1635 RecordDecl::field_iterator Field
= CXXDecl
->field_begin();
1636 unsigned fieldno
= 0;
1637 for (CXXRecordDecl::capture_const_iterator I
= CXXDecl
->captures_begin(),
1638 E
= CXXDecl
->captures_end();
1639 I
!= E
; ++I
, ++Field
, ++fieldno
) {
1640 const LambdaCapture
&C
= *I
;
1641 if (C
.capturesVariable()) {
1642 SourceLocation Loc
= C
.getLocation();
1643 assert(!Field
->isBitField() && "lambdas don't have bitfield members!");
1644 ValueDecl
*V
= C
.getCapturedVar();
1645 StringRef VName
= V
->getName();
1646 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1647 auto Align
= getDeclAlignIfRequired(V
, CGM
.getContext());
1648 llvm::DIType
*FieldType
= createFieldType(
1649 VName
, Field
->getType(), Loc
, Field
->getAccess(),
1650 layout
.getFieldOffset(fieldno
), Align
, VUnit
, RecordTy
, CXXDecl
);
1651 elements
.push_back(FieldType
);
1652 } else if (C
.capturesThis()) {
1653 // TODO: Need to handle 'this' in some way by probably renaming the
1654 // this of the lambda class and having a field member of 'this' or
1655 // by using AT_object_pointer for the function and having that be
1656 // used as 'this' for semantic references.
1657 FieldDecl
*f
= *Field
;
1658 llvm::DIFile
*VUnit
= getOrCreateFile(f
->getLocation());
1659 QualType type
= f
->getType();
1660 llvm::DIType
*fieldType
= createFieldType(
1661 "this", type
, f
->getLocation(), f
->getAccess(),
1662 layout
.getFieldOffset(fieldno
), VUnit
, RecordTy
, CXXDecl
);
1664 elements
.push_back(fieldType
);
1669 llvm::DIDerivedType
*
1670 CGDebugInfo::CreateRecordStaticField(const VarDecl
*Var
, llvm::DIType
*RecordTy
,
1671 const RecordDecl
*RD
) {
1672 // Create the descriptor for the static variable, with or without
1673 // constant initializers.
1674 Var
= Var
->getCanonicalDecl();
1675 llvm::DIFile
*VUnit
= getOrCreateFile(Var
->getLocation());
1676 llvm::DIType
*VTy
= getOrCreateType(Var
->getType(), VUnit
);
1678 unsigned LineNumber
= getLineNumber(Var
->getLocation());
1679 StringRef VName
= Var
->getName();
1680 llvm::Constant
*C
= nullptr;
1681 if (Var
->getInit()) {
1682 const APValue
*Value
= Var
->evaluateValue();
1685 C
= llvm::ConstantInt::get(CGM
.getLLVMContext(), Value
->getInt());
1686 if (Value
->isFloat())
1687 C
= llvm::ConstantFP::get(CGM
.getLLVMContext(), Value
->getFloat());
1691 llvm::DINode::DIFlags Flags
= getAccessFlag(Var
->getAccess(), RD
);
1692 auto Align
= getDeclAlignIfRequired(Var
, CGM
.getContext());
1693 llvm::DIDerivedType
*GV
= DBuilder
.createStaticMemberType(
1694 RecordTy
, VName
, VUnit
, LineNumber
, VTy
, Flags
, C
, Align
);
1695 StaticDataMemberCache
[Var
->getCanonicalDecl()].reset(GV
);
1699 void CGDebugInfo::CollectRecordNormalField(
1700 const FieldDecl
*field
, uint64_t OffsetInBits
, llvm::DIFile
*tunit
,
1701 SmallVectorImpl
<llvm::Metadata
*> &elements
, llvm::DIType
*RecordTy
,
1702 const RecordDecl
*RD
) {
1703 StringRef name
= field
->getName();
1704 QualType type
= field
->getType();
1706 // Ignore unnamed fields unless they're anonymous structs/unions.
1707 if (name
.empty() && !type
->isRecordType())
1710 llvm::DIType
*FieldType
;
1711 if (field
->isBitField()) {
1712 llvm::DIDerivedType
*BitFieldType
;
1713 FieldType
= BitFieldType
= createBitFieldType(field
, RecordTy
, RD
);
1714 if (llvm::DIType
*Separator
=
1715 createBitFieldSeparatorIfNeeded(field
, BitFieldType
, elements
, RD
))
1716 elements
.push_back(Separator
);
1718 auto Align
= getDeclAlignIfRequired(field
, CGM
.getContext());
1719 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(field
);
1721 createFieldType(name
, type
, field
->getLocation(), field
->getAccess(),
1722 OffsetInBits
, Align
, tunit
, RecordTy
, RD
, Annotations
);
1725 elements
.push_back(FieldType
);
1728 void CGDebugInfo::CollectRecordNestedType(
1729 const TypeDecl
*TD
, SmallVectorImpl
<llvm::Metadata
*> &elements
) {
1730 QualType Ty
= CGM
.getContext().getTypeDeclType(TD
);
1731 // Injected class names are not considered nested records.
1732 if (isa
<InjectedClassNameType
>(Ty
))
1734 SourceLocation Loc
= TD
->getLocation();
1735 llvm::DIType
*nestedType
= getOrCreateType(Ty
, getOrCreateFile(Loc
));
1736 elements
.push_back(nestedType
);
1739 void CGDebugInfo::CollectRecordFields(
1740 const RecordDecl
*record
, llvm::DIFile
*tunit
,
1741 SmallVectorImpl
<llvm::Metadata
*> &elements
,
1742 llvm::DICompositeType
*RecordTy
) {
1743 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(record
);
1745 if (CXXDecl
&& CXXDecl
->isLambda())
1746 CollectRecordLambdaFields(CXXDecl
, elements
, RecordTy
);
1748 const ASTRecordLayout
&layout
= CGM
.getContext().getASTRecordLayout(record
);
1750 // Field number for non-static fields.
1751 unsigned fieldNo
= 0;
1753 // Static and non-static members should appear in the same order as
1754 // the corresponding declarations in the source program.
1755 for (const auto *I
: record
->decls())
1756 if (const auto *V
= dyn_cast
<VarDecl
>(I
)) {
1757 if (V
->hasAttr
<NoDebugAttr
>())
1760 // Skip variable template specializations when emitting CodeView. MSVC
1761 // doesn't emit them.
1762 if (CGM
.getCodeGenOpts().EmitCodeView
&&
1763 isa
<VarTemplateSpecializationDecl
>(V
))
1766 if (isa
<VarTemplatePartialSpecializationDecl
>(V
))
1769 // Reuse the existing static member declaration if one exists
1770 auto MI
= StaticDataMemberCache
.find(V
->getCanonicalDecl());
1771 if (MI
!= StaticDataMemberCache
.end()) {
1772 assert(MI
->second
&&
1773 "Static data member declaration should still exist");
1774 elements
.push_back(MI
->second
);
1776 auto Field
= CreateRecordStaticField(V
, RecordTy
, record
);
1777 elements
.push_back(Field
);
1779 } else if (const auto *field
= dyn_cast
<FieldDecl
>(I
)) {
1780 CollectRecordNormalField(field
, layout
.getFieldOffset(fieldNo
), tunit
,
1781 elements
, RecordTy
, record
);
1783 // Bump field number for next field.
1785 } else if (CGM
.getCodeGenOpts().EmitCodeView
) {
1786 // Debug info for nested types is included in the member list only for
1788 if (const auto *nestedType
= dyn_cast
<TypeDecl
>(I
)) {
1789 // MSVC doesn't generate nested type for anonymous struct/union.
1790 if (isa
<RecordDecl
>(I
) &&
1791 cast
<RecordDecl
>(I
)->isAnonymousStructOrUnion())
1793 if (!nestedType
->isImplicit() &&
1794 nestedType
->getDeclContext() == record
)
1795 CollectRecordNestedType(nestedType
, elements
);
1801 llvm::DISubroutineType
*
1802 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl
*Method
,
1803 llvm::DIFile
*Unit
) {
1804 const FunctionProtoType
*Func
= Method
->getType()->getAs
<FunctionProtoType
>();
1805 if (Method
->isStatic())
1806 return cast_or_null
<llvm::DISubroutineType
>(
1807 getOrCreateType(QualType(Func
, 0), Unit
));
1808 return getOrCreateInstanceMethodType(Method
->getThisType(), Func
, Unit
);
1811 llvm::DISubroutineType
*CGDebugInfo::getOrCreateInstanceMethodType(
1812 QualType ThisPtr
, const FunctionProtoType
*Func
, llvm::DIFile
*Unit
) {
1813 FunctionProtoType::ExtProtoInfo EPI
= Func
->getExtProtoInfo();
1814 Qualifiers
&Qc
= EPI
.TypeQuals
;
1816 Qc
.removeVolatile();
1817 Qc
.removeRestrict();
1818 Qc
.removeUnaligned();
1819 // Keep the removed qualifiers in sync with
1820 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1821 // On a 'real' member function type, these qualifiers are carried on the type
1822 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1823 // tags around them. (But, in the raw function types with qualifiers, they have
1824 // to use wrapper types.)
1826 // Add "this" pointer.
1827 const auto *OriginalFunc
= cast
<llvm::DISubroutineType
>(
1828 getOrCreateType(CGM
.getContext().getFunctionType(
1829 Func
->getReturnType(), Func
->getParamTypes(), EPI
),
1831 llvm::DITypeRefArray Args
= OriginalFunc
->getTypeArray();
1832 assert(Args
.size() && "Invalid number of arguments!");
1834 SmallVector
<llvm::Metadata
*, 16> Elts
;
1836 // First element is always return type. For 'void' functions it is NULL.
1837 Elts
.push_back(Args
[0]);
1839 // "this" pointer is always first argument.
1840 const CXXRecordDecl
*RD
= ThisPtr
->getPointeeCXXRecordDecl();
1841 if (isa
<ClassTemplateSpecializationDecl
>(RD
)) {
1842 // Create pointer type directly in this case.
1843 const PointerType
*ThisPtrTy
= cast
<PointerType
>(ThisPtr
);
1844 uint64_t Size
= CGM
.getContext().getTypeSize(ThisPtrTy
);
1845 auto Align
= getTypeAlignIfRequired(ThisPtrTy
, CGM
.getContext());
1846 llvm::DIType
*PointeeType
=
1847 getOrCreateType(ThisPtrTy
->getPointeeType(), Unit
);
1848 llvm::DIType
*ThisPtrType
=
1849 DBuilder
.createPointerType(PointeeType
, Size
, Align
);
1850 TypeCache
[ThisPtr
.getAsOpaquePtr()].reset(ThisPtrType
);
1851 // TODO: This and the artificial type below are misleading, the
1852 // types aren't artificial the argument is, but the current
1853 // metadata doesn't represent that.
1854 ThisPtrType
= DBuilder
.createObjectPointerType(ThisPtrType
);
1855 Elts
.push_back(ThisPtrType
);
1857 llvm::DIType
*ThisPtrType
= getOrCreateType(ThisPtr
, Unit
);
1858 TypeCache
[ThisPtr
.getAsOpaquePtr()].reset(ThisPtrType
);
1859 ThisPtrType
= DBuilder
.createObjectPointerType(ThisPtrType
);
1860 Elts
.push_back(ThisPtrType
);
1863 // Copy rest of the arguments.
1864 for (unsigned i
= 1, e
= Args
.size(); i
!= e
; ++i
)
1865 Elts
.push_back(Args
[i
]);
1867 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(Elts
);
1869 return DBuilder
.createSubroutineType(EltTypeArray
, OriginalFunc
->getFlags(),
1870 getDwarfCC(Func
->getCallConv()));
1873 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1874 /// inside a function.
1875 static bool isFunctionLocalClass(const CXXRecordDecl
*RD
) {
1876 if (const auto *NRD
= dyn_cast
<CXXRecordDecl
>(RD
->getDeclContext()))
1877 return isFunctionLocalClass(NRD
);
1878 if (isa
<FunctionDecl
>(RD
->getDeclContext()))
1883 llvm::DISubprogram
*CGDebugInfo::CreateCXXMemberFunction(
1884 const CXXMethodDecl
*Method
, llvm::DIFile
*Unit
, llvm::DIType
*RecordTy
) {
1886 isa
<CXXConstructorDecl
>(Method
) || isa
<CXXDestructorDecl
>(Method
);
1888 StringRef MethodName
= getFunctionName(Method
);
1889 llvm::DISubroutineType
*MethodTy
= getOrCreateMethodType(Method
, Unit
);
1891 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1892 // make sense to give a single ctor/dtor a linkage name.
1893 StringRef MethodLinkageName
;
1894 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1895 // property to use here. It may've been intended to model "is non-external
1896 // type" but misses cases of non-function-local but non-external classes such
1897 // as those in anonymous namespaces as well as the reverse - external types
1898 // that are function local, such as those in (non-local) inline functions.
1899 if (!IsCtorOrDtor
&& !isFunctionLocalClass(Method
->getParent()))
1900 MethodLinkageName
= CGM
.getMangledName(Method
);
1902 // Get the location for the method.
1903 llvm::DIFile
*MethodDefUnit
= nullptr;
1904 unsigned MethodLine
= 0;
1905 if (!Method
->isImplicit()) {
1906 MethodDefUnit
= getOrCreateFile(Method
->getLocation());
1907 MethodLine
= getLineNumber(Method
->getLocation());
1910 // Collect virtual method info.
1911 llvm::DIType
*ContainingType
= nullptr;
1912 unsigned VIndex
= 0;
1913 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1914 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
1915 int ThisAdjustment
= 0;
1917 if (VTableContextBase::hasVtableSlot(Method
)) {
1918 if (Method
->isPure())
1919 SPFlags
|= llvm::DISubprogram::SPFlagPureVirtual
;
1921 SPFlags
|= llvm::DISubprogram::SPFlagVirtual
;
1923 if (CGM
.getTarget().getCXXABI().isItaniumFamily()) {
1924 // It doesn't make sense to give a virtual destructor a vtable index,
1925 // since a single destructor has two entries in the vtable.
1926 if (!isa
<CXXDestructorDecl
>(Method
))
1927 VIndex
= CGM
.getItaniumVTableContext().getMethodVTableIndex(Method
);
1929 // Emit MS ABI vftable information. There is only one entry for the
1931 const auto *DD
= dyn_cast
<CXXDestructorDecl
>(Method
);
1932 GlobalDecl GD
= DD
? GlobalDecl(DD
, Dtor_Deleting
) : GlobalDecl(Method
);
1933 MethodVFTableLocation ML
=
1934 CGM
.getMicrosoftVTableContext().getMethodVFTableLocation(GD
);
1937 // CodeView only records the vftable offset in the class that introduces
1938 // the virtual method. This is possible because, unlike Itanium, the MS
1939 // C++ ABI does not include all virtual methods from non-primary bases in
1940 // the vtable for the most derived class. For example, if C inherits from
1941 // A and B, C's primary vftable will not include B's virtual methods.
1942 if (Method
->size_overridden_methods() == 0)
1943 Flags
|= llvm::DINode::FlagIntroducedVirtual
;
1945 // The 'this' adjustment accounts for both the virtual and non-virtual
1946 // portions of the adjustment. Presumably the debugger only uses it when
1947 // it knows the dynamic type of an object.
1948 ThisAdjustment
= CGM
.getCXXABI()
1949 .getVirtualFunctionPrologueThisAdjustment(GD
)
1952 ContainingType
= RecordTy
;
1955 if (Method
->getCanonicalDecl()->isDeleted())
1956 SPFlags
|= llvm::DISubprogram::SPFlagDeleted
;
1958 if (Method
->isNoReturn())
1959 Flags
|= llvm::DINode::FlagNoReturn
;
1961 if (Method
->isStatic())
1962 Flags
|= llvm::DINode::FlagStaticMember
;
1963 if (Method
->isImplicit())
1964 Flags
|= llvm::DINode::FlagArtificial
;
1965 Flags
|= getAccessFlag(Method
->getAccess(), Method
->getParent());
1966 if (const auto *CXXC
= dyn_cast
<CXXConstructorDecl
>(Method
)) {
1967 if (CXXC
->isExplicit())
1968 Flags
|= llvm::DINode::FlagExplicit
;
1969 } else if (const auto *CXXC
= dyn_cast
<CXXConversionDecl
>(Method
)) {
1970 if (CXXC
->isExplicit())
1971 Flags
|= llvm::DINode::FlagExplicit
;
1973 if (Method
->hasPrototype())
1974 Flags
|= llvm::DINode::FlagPrototyped
;
1975 if (Method
->getRefQualifier() == RQ_LValue
)
1976 Flags
|= llvm::DINode::FlagLValueReference
;
1977 if (Method
->getRefQualifier() == RQ_RValue
)
1978 Flags
|= llvm::DINode::FlagRValueReference
;
1979 if (!Method
->isExternallyVisible())
1980 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
1981 if (CGM
.getLangOpts().Optimize
)
1982 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
1984 // In this debug mode, emit type info for a class when its constructor type
1986 if (DebugKind
== llvm::codegenoptions::DebugInfoConstructor
)
1987 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(Method
))
1988 completeUnusedClass(*CD
->getParent());
1990 llvm::DINodeArray TParamsArray
= CollectFunctionTemplateParams(Method
, Unit
);
1991 llvm::DISubprogram
*SP
= DBuilder
.createMethod(
1992 RecordTy
, MethodName
, MethodLinkageName
, MethodDefUnit
, MethodLine
,
1993 MethodTy
, VIndex
, ThisAdjustment
, ContainingType
, Flags
, SPFlags
,
1994 TParamsArray
.get());
1996 SPCache
[Method
->getCanonicalDecl()].reset(SP
);
2001 void CGDebugInfo::CollectCXXMemberFunctions(
2002 const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2003 SmallVectorImpl
<llvm::Metadata
*> &EltTys
, llvm::DIType
*RecordTy
) {
2005 // Since we want more than just the individual member decls if we
2006 // have templated functions iterate over every declaration to gather
2008 for (const auto *I
: RD
->decls()) {
2009 const auto *Method
= dyn_cast
<CXXMethodDecl
>(I
);
2010 // If the member is implicit, don't add it to the member list. This avoids
2011 // the member being added to type units by LLVM, while still allowing it
2012 // to be emitted into the type declaration/reference inside the compile
2014 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2015 // FIXME: Handle Using(Shadow?)Decls here to create
2016 // DW_TAG_imported_declarations inside the class for base decls brought into
2017 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2018 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2020 if (!Method
|| Method
->isImplicit() || Method
->hasAttr
<NoDebugAttr
>())
2023 if (Method
->getType()->castAs
<FunctionProtoType
>()->getContainedAutoType())
2026 // Reuse the existing member function declaration if it exists.
2027 // It may be associated with the declaration of the type & should be
2028 // reused as we're building the definition.
2030 // This situation can arise in the vtable-based debug info reduction where
2031 // implicit members are emitted in a non-vtable TU.
2032 auto MI
= SPCache
.find(Method
->getCanonicalDecl());
2033 EltTys
.push_back(MI
== SPCache
.end()
2034 ? CreateCXXMemberFunction(Method
, Unit
, RecordTy
)
2035 : static_cast<llvm::Metadata
*>(MI
->second
));
2039 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2040 SmallVectorImpl
<llvm::Metadata
*> &EltTys
,
2041 llvm::DIType
*RecordTy
) {
2042 llvm::DenseSet
<CanonicalDeclPtr
<const CXXRecordDecl
>> SeenTypes
;
2043 CollectCXXBasesAux(RD
, Unit
, EltTys
, RecordTy
, RD
->bases(), SeenTypes
,
2044 llvm::DINode::FlagZero
);
2046 // If we are generating CodeView debug info, we also need to emit records for
2047 // indirect virtual base classes.
2048 if (CGM
.getCodeGenOpts().EmitCodeView
) {
2049 CollectCXXBasesAux(RD
, Unit
, EltTys
, RecordTy
, RD
->vbases(), SeenTypes
,
2050 llvm::DINode::FlagIndirectVirtualBase
);
2054 void CGDebugInfo::CollectCXXBasesAux(
2055 const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2056 SmallVectorImpl
<llvm::Metadata
*> &EltTys
, llvm::DIType
*RecordTy
,
2057 const CXXRecordDecl::base_class_const_range
&Bases
,
2058 llvm::DenseSet
<CanonicalDeclPtr
<const CXXRecordDecl
>> &SeenTypes
,
2059 llvm::DINode::DIFlags StartingFlags
) {
2060 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
2061 for (const auto &BI
: Bases
) {
2063 cast
<CXXRecordDecl
>(BI
.getType()->castAs
<RecordType
>()->getDecl());
2064 if (!SeenTypes
.insert(Base
).second
)
2066 auto *BaseTy
= getOrCreateType(BI
.getType(), Unit
);
2067 llvm::DINode::DIFlags BFlags
= StartingFlags
;
2068 uint64_t BaseOffset
;
2069 uint32_t VBPtrOffset
= 0;
2071 if (BI
.isVirtual()) {
2072 if (CGM
.getTarget().getCXXABI().isItaniumFamily()) {
2073 // virtual base offset offset is -ve. The code generator emits dwarf
2074 // expression where it expects +ve number.
2075 BaseOffset
= 0 - CGM
.getItaniumVTableContext()
2076 .getVirtualBaseOffsetOffset(RD
, Base
)
2079 // In the MS ABI, store the vbtable offset, which is analogous to the
2080 // vbase offset offset in Itanium.
2082 4 * CGM
.getMicrosoftVTableContext().getVBTableIndex(RD
, Base
);
2083 VBPtrOffset
= CGM
.getContext()
2084 .getASTRecordLayout(RD
)
2088 BFlags
|= llvm::DINode::FlagVirtual
;
2090 BaseOffset
= CGM
.getContext().toBits(RL
.getBaseClassOffset(Base
));
2091 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2092 // BI->isVirtual() and bits when not.
2094 BFlags
|= getAccessFlag(BI
.getAccessSpecifier(), RD
);
2095 llvm::DIType
*DTy
= DBuilder
.createInheritance(RecordTy
, BaseTy
, BaseOffset
,
2096 VBPtrOffset
, BFlags
);
2097 EltTys
.push_back(DTy
);
2102 CGDebugInfo::CollectTemplateParams(std::optional
<TemplateArgs
> OArgs
,
2103 llvm::DIFile
*Unit
) {
2105 return llvm::DINodeArray();
2106 TemplateArgs
&Args
= *OArgs
;
2107 SmallVector
<llvm::Metadata
*, 16> TemplateParams
;
2108 for (unsigned i
= 0, e
= Args
.Args
.size(); i
!= e
; ++i
) {
2109 const TemplateArgument
&TA
= Args
.Args
[i
];
2111 const bool defaultParameter
= TA
.getIsDefaulted();
2113 Name
= Args
.TList
->getParam(i
)->getName();
2115 switch (TA
.getKind()) {
2116 case TemplateArgument::Type
: {
2117 llvm::DIType
*TTy
= getOrCreateType(TA
.getAsType(), Unit
);
2118 TemplateParams
.push_back(DBuilder
.createTemplateTypeParameter(
2119 TheCU
, Name
, TTy
, defaultParameter
));
2122 case TemplateArgument::Integral
: {
2123 llvm::DIType
*TTy
= getOrCreateType(TA
.getIntegralType(), Unit
);
2124 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2125 TheCU
, Name
, TTy
, defaultParameter
,
2126 llvm::ConstantInt::get(CGM
.getLLVMContext(), TA
.getAsIntegral())));
2128 case TemplateArgument::Declaration
: {
2129 const ValueDecl
*D
= TA
.getAsDecl();
2130 QualType T
= TA
.getParamTypeForDecl().getDesugaredType(CGM
.getContext());
2131 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2132 llvm::Constant
*V
= nullptr;
2133 // Skip retrieve the value if that template parameter has cuda device
2134 // attribute, i.e. that value is not available at the host side.
2135 if (!CGM
.getLangOpts().CUDA
|| CGM
.getLangOpts().CUDAIsDevice
||
2136 !D
->hasAttr
<CUDADeviceAttr
>()) {
2137 // Variable pointer template parameters have a value that is the address
2139 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
2140 V
= CGM
.GetAddrOfGlobalVar(VD
);
2141 // Member function pointers have special support for building them,
2142 // though this is currently unsupported in LLVM CodeGen.
2143 else if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
);
2144 MD
&& MD
->isImplicitObjectMemberFunction())
2145 V
= CGM
.getCXXABI().EmitMemberFunctionPointer(MD
);
2146 else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
2147 V
= CGM
.GetAddrOfFunction(FD
);
2148 // Member data pointers have special handling too to compute the fixed
2149 // offset within the object.
2150 else if (const auto *MPT
=
2151 dyn_cast
<MemberPointerType
>(T
.getTypePtr())) {
2152 // These five lines (& possibly the above member function pointer
2153 // handling) might be able to be refactored to use similar code in
2154 // CodeGenModule::getMemberPointerConstant
2155 uint64_t fieldOffset
= CGM
.getContext().getFieldOffset(D
);
2157 CGM
.getContext().toCharUnitsFromBits((int64_t)fieldOffset
);
2158 V
= CGM
.getCXXABI().EmitMemberDataPointer(MPT
, chars
);
2159 } else if (const auto *GD
= dyn_cast
<MSGuidDecl
>(D
)) {
2160 V
= CGM
.GetAddrOfMSGuidDecl(GD
).getPointer();
2161 } else if (const auto *TPO
= dyn_cast
<TemplateParamObjectDecl
>(D
)) {
2162 if (T
->isRecordType())
2163 V
= ConstantEmitter(CGM
).emitAbstract(
2164 SourceLocation(), TPO
->getValue(), TPO
->getType());
2166 V
= CGM
.GetAddrOfTemplateParamObject(TPO
).getPointer();
2168 assert(V
&& "Failed to find template parameter pointer");
2169 V
= V
->stripPointerCasts();
2171 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2172 TheCU
, Name
, TTy
, defaultParameter
, cast_or_null
<llvm::Constant
>(V
)));
2174 case TemplateArgument::NullPtr
: {
2175 QualType T
= TA
.getNullPtrType();
2176 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2177 llvm::Constant
*V
= nullptr;
2178 // Special case member data pointer null values since they're actually -1
2180 if (const auto *MPT
= dyn_cast
<MemberPointerType
>(T
.getTypePtr()))
2181 // But treat member function pointers as simple zero integers because
2182 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2183 // CodeGen grows handling for values of non-null member function
2184 // pointers then perhaps we could remove this special case and rely on
2185 // EmitNullMemberPointer for member function pointers.
2186 if (MPT
->isMemberDataPointer())
2187 V
= CGM
.getCXXABI().EmitNullMemberPointer(MPT
);
2189 V
= llvm::ConstantInt::get(CGM
.Int8Ty
, 0);
2190 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2191 TheCU
, Name
, TTy
, defaultParameter
, V
));
2193 case TemplateArgument::Template
: {
2194 std::string QualName
;
2195 llvm::raw_string_ostream
OS(QualName
);
2196 TA
.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2197 OS
, getPrintingPolicy());
2198 TemplateParams
.push_back(DBuilder
.createTemplateTemplateParameter(
2199 TheCU
, Name
, nullptr, OS
.str(), defaultParameter
));
2202 case TemplateArgument::Pack
:
2203 TemplateParams
.push_back(DBuilder
.createTemplateParameterPack(
2204 TheCU
, Name
, nullptr,
2205 CollectTemplateParams({{nullptr, TA
.getPackAsArray()}}, Unit
)));
2207 case TemplateArgument::Expression
: {
2208 const Expr
*E
= TA
.getAsExpr();
2209 QualType T
= E
->getType();
2211 T
= CGM
.getContext().getLValueReferenceType(T
);
2212 llvm::Constant
*V
= ConstantEmitter(CGM
).emitAbstract(E
, T
);
2213 assert(V
&& "Expression in template argument isn't constant");
2214 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2215 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2216 TheCU
, Name
, TTy
, defaultParameter
, V
->stripPointerCasts()));
2218 // And the following should never occur:
2219 case TemplateArgument::TemplateExpansion
:
2220 case TemplateArgument::Null
:
2222 "These argument types shouldn't exist in concrete types");
2225 return DBuilder
.getOrCreateArray(TemplateParams
);
2228 std::optional
<CGDebugInfo::TemplateArgs
>
2229 CGDebugInfo::GetTemplateArgs(const FunctionDecl
*FD
) const {
2230 if (FD
->getTemplatedKind() ==
2231 FunctionDecl::TK_FunctionTemplateSpecialization
) {
2232 const TemplateParameterList
*TList
= FD
->getTemplateSpecializationInfo()
2234 ->getTemplateParameters();
2235 return {{TList
, FD
->getTemplateSpecializationArgs()->asArray()}};
2237 return std::nullopt
;
2239 std::optional
<CGDebugInfo::TemplateArgs
>
2240 CGDebugInfo::GetTemplateArgs(const VarDecl
*VD
) const {
2241 // Always get the full list of parameters, not just the ones from the
2242 // specialization. A partial specialization may have fewer parameters than
2243 // there are arguments.
2244 auto *TS
= dyn_cast
<VarTemplateSpecializationDecl
>(VD
);
2246 return std::nullopt
;
2247 VarTemplateDecl
*T
= TS
->getSpecializedTemplate();
2248 const TemplateParameterList
*TList
= T
->getTemplateParameters();
2249 auto TA
= TS
->getTemplateArgs().asArray();
2250 return {{TList
, TA
}};
2252 std::optional
<CGDebugInfo::TemplateArgs
>
2253 CGDebugInfo::GetTemplateArgs(const RecordDecl
*RD
) const {
2254 if (auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
2255 // Always get the full list of parameters, not just the ones from the
2256 // specialization. A partial specialization may have fewer parameters than
2257 // there are arguments.
2258 TemplateParameterList
*TPList
=
2259 TSpecial
->getSpecializedTemplate()->getTemplateParameters();
2260 const TemplateArgumentList
&TAList
= TSpecial
->getTemplateArgs();
2261 return {{TPList
, TAList
.asArray()}};
2263 return std::nullopt
;
2267 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl
*FD
,
2268 llvm::DIFile
*Unit
) {
2269 return CollectTemplateParams(GetTemplateArgs(FD
), Unit
);
2272 llvm::DINodeArray
CGDebugInfo::CollectVarTemplateParams(const VarDecl
*VL
,
2273 llvm::DIFile
*Unit
) {
2274 return CollectTemplateParams(GetTemplateArgs(VL
), Unit
);
2277 llvm::DINodeArray
CGDebugInfo::CollectCXXTemplateParams(const RecordDecl
*RD
,
2278 llvm::DIFile
*Unit
) {
2279 return CollectTemplateParams(GetTemplateArgs(RD
), Unit
);
2282 llvm::DINodeArray
CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl
*D
) {
2283 if (!D
->hasAttr
<BTFDeclTagAttr
>())
2286 SmallVector
<llvm::Metadata
*, 4> Annotations
;
2287 for (const auto *I
: D
->specific_attrs
<BTFDeclTagAttr
>()) {
2288 llvm::Metadata
*Ops
[2] = {
2289 llvm::MDString::get(CGM
.getLLVMContext(), StringRef("btf_decl_tag")),
2290 llvm::MDString::get(CGM
.getLLVMContext(), I
->getBTFDeclTag())};
2291 Annotations
.push_back(llvm::MDNode::get(CGM
.getLLVMContext(), Ops
));
2293 return DBuilder
.getOrCreateArray(Annotations
);
2296 llvm::DIType
*CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile
*Unit
) {
2298 return VTablePtrType
;
2300 ASTContext
&Context
= CGM
.getContext();
2303 llvm::Metadata
*STy
= getOrCreateType(Context
.IntTy
, Unit
);
2304 llvm::DITypeRefArray SElements
= DBuilder
.getOrCreateTypeArray(STy
);
2305 llvm::DIType
*SubTy
= DBuilder
.createSubroutineType(SElements
);
2306 unsigned Size
= Context
.getTypeSize(Context
.VoidPtrTy
);
2307 unsigned VtblPtrAddressSpace
= CGM
.getTarget().getVtblPtrAddressSpace();
2308 std::optional
<unsigned> DWARFAddressSpace
=
2309 CGM
.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace
);
2311 llvm::DIType
*vtbl_ptr_type
= DBuilder
.createPointerType(
2312 SubTy
, Size
, 0, DWARFAddressSpace
, "__vtbl_ptr_type");
2313 VTablePtrType
= DBuilder
.createPointerType(vtbl_ptr_type
, Size
);
2314 return VTablePtrType
;
2317 StringRef
CGDebugInfo::getVTableName(const CXXRecordDecl
*RD
) {
2318 // Copy the gdb compatible name on the side and use its reference.
2319 return internString("_vptr$", RD
->getNameAsString());
2322 StringRef
CGDebugInfo::getDynamicInitializerName(const VarDecl
*VD
,
2323 DynamicInitKind StubKind
,
2324 llvm::Function
*InitFn
) {
2325 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2327 if (!CGM
.getCodeGenOpts().EmitCodeView
||
2328 StubKind
== DynamicInitKind::GlobalArrayDestructor
)
2329 return InitFn
->getName();
2331 // Print the normal qualified name for the variable, then break off the last
2332 // NNS, and add the appropriate other text. Clang always prints the global
2333 // variable name without template arguments, so we can use rsplit("::") and
2334 // then recombine the pieces.
2335 SmallString
<128> QualifiedGV
;
2339 llvm::raw_svector_ostream
OS(QualifiedGV
);
2340 VD
->printQualifiedName(OS
, getPrintingPolicy());
2341 std::tie(Quals
, GVName
) = OS
.str().rsplit("::");
2343 std::swap(Quals
, GVName
);
2346 SmallString
<128> InitName
;
2347 llvm::raw_svector_ostream
OS(InitName
);
2349 OS
<< Quals
<< "::";
2352 case DynamicInitKind::NoStub
:
2353 case DynamicInitKind::GlobalArrayDestructor
:
2354 llvm_unreachable("not an initializer");
2355 case DynamicInitKind::Initializer
:
2356 OS
<< "`dynamic initializer for '";
2358 case DynamicInitKind::AtExit
:
2359 OS
<< "`dynamic atexit destructor for '";
2365 // Add any template specialization args.
2366 if (const auto *VTpl
= dyn_cast
<VarTemplateSpecializationDecl
>(VD
)) {
2367 printTemplateArgumentList(OS
, VTpl
->getTemplateArgs().asArray(),
2368 getPrintingPolicy());
2373 return internString(OS
.str());
2376 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2377 SmallVectorImpl
<llvm::Metadata
*> &EltTys
) {
2378 // If this class is not dynamic then there is not any vtable info to collect.
2379 if (!RD
->isDynamicClass())
2382 // Don't emit any vtable shape or vptr info if this class doesn't have an
2383 // extendable vfptr. This can happen if the class doesn't have virtual
2384 // methods, or in the MS ABI if those virtual methods only come from virtually
2386 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
2387 if (!RL
.hasExtendableVFPtr())
2390 // CodeView needs to know how large the vtable of every dynamic class is, so
2391 // emit a special named pointer type into the element list. The vptr type
2392 // points to this type as well.
2393 llvm::DIType
*VPtrTy
= nullptr;
2394 bool NeedVTableShape
= CGM
.getCodeGenOpts().EmitCodeView
&&
2395 CGM
.getTarget().getCXXABI().isMicrosoft();
2396 if (NeedVTableShape
) {
2398 CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
2399 const VTableLayout
&VFTLayout
=
2400 CGM
.getMicrosoftVTableContext().getVFTableLayout(RD
, CharUnits::Zero());
2401 unsigned VSlotCount
=
2402 VFTLayout
.vtable_components().size() - CGM
.getLangOpts().RTTIData
;
2403 unsigned VTableWidth
= PtrWidth
* VSlotCount
;
2404 unsigned VtblPtrAddressSpace
= CGM
.getTarget().getVtblPtrAddressSpace();
2405 std::optional
<unsigned> DWARFAddressSpace
=
2406 CGM
.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace
);
2408 // Create a very wide void* type and insert it directly in the element list.
2409 llvm::DIType
*VTableType
= DBuilder
.createPointerType(
2410 nullptr, VTableWidth
, 0, DWARFAddressSpace
, "__vtbl_ptr_type");
2411 EltTys
.push_back(VTableType
);
2413 // The vptr is a pointer to this special vtable type.
2414 VPtrTy
= DBuilder
.createPointerType(VTableType
, PtrWidth
);
2417 // If there is a primary base then the artificial vptr member lives there.
2418 if (RL
.getPrimaryBase())
2422 VPtrTy
= getOrCreateVTablePtrType(Unit
);
2424 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
2425 llvm::DIType
*VPtrMember
=
2426 DBuilder
.createMemberType(Unit
, getVTableName(RD
), Unit
, 0, Size
, 0, 0,
2427 llvm::DINode::FlagArtificial
, VPtrTy
);
2428 EltTys
.push_back(VPtrMember
);
2431 llvm::DIType
*CGDebugInfo::getOrCreateRecordType(QualType RTy
,
2432 SourceLocation Loc
) {
2433 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
2434 llvm::DIType
*T
= getOrCreateType(RTy
, getOrCreateFile(Loc
));
2438 llvm::DIType
*CGDebugInfo::getOrCreateInterfaceType(QualType D
,
2439 SourceLocation Loc
) {
2440 return getOrCreateStandaloneType(D
, Loc
);
2443 llvm::DIType
*CGDebugInfo::getOrCreateStandaloneType(QualType D
,
2444 SourceLocation Loc
) {
2445 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
2446 assert(!D
.isNull() && "null type");
2447 llvm::DIType
*T
= getOrCreateType(D
, getOrCreateFile(Loc
));
2448 assert(T
&& "could not create debug info for type");
2450 RetainedTypes
.push_back(D
.getAsOpaquePtr());
2454 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase
*CI
,
2455 QualType AllocatedTy
,
2456 SourceLocation Loc
) {
2457 if (CGM
.getCodeGenOpts().getDebugInfo() <=
2458 llvm::codegenoptions::DebugLineTablesOnly
)
2461 if (AllocatedTy
->isVoidType())
2462 node
= llvm::MDNode::get(CGM
.getLLVMContext(), std::nullopt
);
2464 node
= getOrCreateType(AllocatedTy
, getOrCreateFile(Loc
));
2466 CI
->setMetadata("heapallocsite", node
);
2469 void CGDebugInfo::completeType(const EnumDecl
*ED
) {
2470 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
2472 QualType Ty
= CGM
.getContext().getEnumType(ED
);
2473 void *TyPtr
= Ty
.getAsOpaquePtr();
2474 auto I
= TypeCache
.find(TyPtr
);
2475 if (I
== TypeCache
.end() || !cast
<llvm::DIType
>(I
->second
)->isForwardDecl())
2477 llvm::DIType
*Res
= CreateTypeDefinition(Ty
->castAs
<EnumType
>());
2478 assert(!Res
->isForwardDecl());
2479 TypeCache
[TyPtr
].reset(Res
);
2482 void CGDebugInfo::completeType(const RecordDecl
*RD
) {
2483 if (DebugKind
> llvm::codegenoptions::LimitedDebugInfo
||
2484 !CGM
.getLangOpts().CPlusPlus
)
2485 completeRequiredType(RD
);
2488 /// Return true if the class or any of its methods are marked dllimport.
2489 static bool isClassOrMethodDLLImport(const CXXRecordDecl
*RD
) {
2490 if (RD
->hasAttr
<DLLImportAttr
>())
2492 for (const CXXMethodDecl
*MD
: RD
->methods())
2493 if (MD
->hasAttr
<DLLImportAttr
>())
2498 /// Does a type definition exist in an imported clang module?
2499 static bool isDefinedInClangModule(const RecordDecl
*RD
) {
2500 // Only definitions that where imported from an AST file come from a module.
2501 if (!RD
|| !RD
->isFromASTFile())
2503 // Anonymous entities cannot be addressed. Treat them as not from module.
2504 if (!RD
->isExternallyVisible() && RD
->getName().empty())
2506 if (auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
)) {
2507 if (!CXXDecl
->isCompleteDefinition())
2509 // Check wether RD is a template.
2510 auto TemplateKind
= CXXDecl
->getTemplateSpecializationKind();
2511 if (TemplateKind
!= TSK_Undeclared
) {
2512 // Unfortunately getOwningModule() isn't accurate enough to find the
2513 // owning module of a ClassTemplateSpecializationDecl that is inside a
2514 // namespace spanning multiple modules.
2515 bool Explicit
= false;
2516 if (auto *TD
= dyn_cast
<ClassTemplateSpecializationDecl
>(CXXDecl
))
2517 Explicit
= TD
->isExplicitInstantiationOrSpecialization();
2518 if (!Explicit
&& CXXDecl
->getEnclosingNamespaceContext())
2520 // This is a template, check the origin of the first member.
2521 if (CXXDecl
->field_begin() == CXXDecl
->field_end())
2522 return TemplateKind
== TSK_ExplicitInstantiationDeclaration
;
2523 if (!CXXDecl
->field_begin()->isFromASTFile())
2530 void CGDebugInfo::completeClassData(const RecordDecl
*RD
) {
2531 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
2532 if (CXXRD
->isDynamicClass() &&
2533 CGM
.getVTableLinkage(CXXRD
) ==
2534 llvm::GlobalValue::AvailableExternallyLinkage
&&
2535 !isClassOrMethodDLLImport(CXXRD
))
2538 if (DebugTypeExtRefs
&& isDefinedInClangModule(RD
->getDefinition()))
2544 void CGDebugInfo::completeClass(const RecordDecl
*RD
) {
2545 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
2547 QualType Ty
= CGM
.getContext().getRecordType(RD
);
2548 void *TyPtr
= Ty
.getAsOpaquePtr();
2549 auto I
= TypeCache
.find(TyPtr
);
2550 if (I
!= TypeCache
.end() && !cast
<llvm::DIType
>(I
->second
)->isForwardDecl())
2553 // We want the canonical definition of the structure to not
2554 // be the typedef. Since that would lead to circular typedef
2556 auto [Res
, PrefRes
] = CreateTypeDefinition(Ty
->castAs
<RecordType
>());
2557 assert(!Res
->isForwardDecl());
2558 TypeCache
[TyPtr
].reset(Res
);
2561 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I
,
2562 CXXRecordDecl::method_iterator End
) {
2563 for (CXXMethodDecl
*MD
: llvm::make_range(I
, End
))
2564 if (FunctionDecl
*Tmpl
= MD
->getInstantiatedFromMemberFunction())
2565 if (!Tmpl
->isImplicit() && Tmpl
->isThisDeclarationADefinition() &&
2566 !MD
->getMemberSpecializationInfo()->isExplicitSpecialization())
2571 static bool canUseCtorHoming(const CXXRecordDecl
*RD
) {
2572 // Constructor homing can be used for classes that cannnot be constructed
2573 // without emitting code for one of their constructors. This is classes that
2574 // don't have trivial or constexpr constructors, or can be created from
2575 // aggregate initialization. Also skip lambda objects because they don't call
2578 // Skip this optimization if the class or any of its methods are marked
2580 if (isClassOrMethodDLLImport(RD
))
2583 if (RD
->isLambda() || RD
->isAggregate() ||
2584 RD
->hasTrivialDefaultConstructor() ||
2585 RD
->hasConstexprNonCopyMoveConstructor())
2588 for (const CXXConstructorDecl
*Ctor
: RD
->ctors()) {
2589 if (Ctor
->isCopyOrMoveConstructor())
2591 if (!Ctor
->isDeleted())
2597 static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind
,
2598 bool DebugTypeExtRefs
, const RecordDecl
*RD
,
2599 const LangOptions
&LangOpts
) {
2600 if (DebugTypeExtRefs
&& isDefinedInClangModule(RD
->getDefinition()))
2603 if (auto *ES
= RD
->getASTContext().getExternalSource())
2604 if (ES
->hasExternalDefinitions(RD
) == ExternalASTSource::EK_Always
)
2607 // Only emit forward declarations in line tables only to keep debug info size
2608 // small. This only applies to CodeView, since we don't emit types in DWARF
2609 // line tables only.
2610 if (DebugKind
== llvm::codegenoptions::DebugLineTablesOnly
)
2613 if (DebugKind
> llvm::codegenoptions::LimitedDebugInfo
||
2614 RD
->hasAttr
<StandaloneDebugAttr
>())
2617 if (!LangOpts
.CPlusPlus
)
2620 if (!RD
->isCompleteDefinitionRequired())
2623 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
);
2628 // Only emit complete debug info for a dynamic class when its vtable is
2629 // emitted. However, Microsoft debuggers don't resolve type information
2630 // across DLL boundaries, so skip this optimization if the class or any of its
2631 // methods are marked dllimport. This isn't a complete solution, since objects
2632 // without any dllimport methods can be used in one DLL and constructed in
2633 // another, but it is the current behavior of LimitedDebugInfo.
2634 if (CXXDecl
->hasDefinition() && CXXDecl
->isDynamicClass() &&
2635 !isClassOrMethodDLLImport(CXXDecl
))
2638 TemplateSpecializationKind Spec
= TSK_Undeclared
;
2639 if (const auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
2640 Spec
= SD
->getSpecializationKind();
2642 if (Spec
== TSK_ExplicitInstantiationDeclaration
&&
2643 hasExplicitMemberDefinition(CXXDecl
->method_begin(),
2644 CXXDecl
->method_end()))
2647 // In constructor homing mode, only emit complete debug info for a class
2648 // when its constructor is emitted.
2649 if ((DebugKind
== llvm::codegenoptions::DebugInfoConstructor
) &&
2650 canUseCtorHoming(CXXDecl
))
2656 void CGDebugInfo::completeRequiredType(const RecordDecl
*RD
) {
2657 if (shouldOmitDefinition(DebugKind
, DebugTypeExtRefs
, RD
, CGM
.getLangOpts()))
2660 QualType Ty
= CGM
.getContext().getRecordType(RD
);
2661 llvm::DIType
*T
= getTypeOrNull(Ty
);
2662 if (T
&& T
->isForwardDecl())
2663 completeClassData(RD
);
2666 llvm::DIType
*CGDebugInfo::CreateType(const RecordType
*Ty
) {
2667 RecordDecl
*RD
= Ty
->getDecl();
2668 llvm::DIType
*T
= cast_or_null
<llvm::DIType
>(getTypeOrNull(QualType(Ty
, 0)));
2669 if (T
|| shouldOmitDefinition(DebugKind
, DebugTypeExtRefs
, RD
,
2670 CGM
.getLangOpts())) {
2672 T
= getOrCreateRecordFwdDecl(Ty
, getDeclContextDescriptor(RD
));
2676 auto [Def
, Pref
] = CreateTypeDefinition(Ty
);
2678 return Pref
? Pref
: Def
;
2681 llvm::DIType
*CGDebugInfo::GetPreferredNameType(const CXXRecordDecl
*RD
,
2682 llvm::DIFile
*Unit
) {
2686 auto const *PNA
= RD
->getAttr
<PreferredNameAttr
>();
2690 return getOrCreateType(PNA
->getTypedefType(), Unit
);
2693 std::pair
<llvm::DIType
*, llvm::DIType
*>
2694 CGDebugInfo::CreateTypeDefinition(const RecordType
*Ty
) {
2695 RecordDecl
*RD
= Ty
->getDecl();
2697 // Get overall information about the record type for the debug info.
2698 llvm::DIFile
*DefUnit
= getOrCreateFile(RD
->getLocation());
2700 // Records and classes and unions can all be recursive. To handle them, we
2701 // first generate a debug descriptor for the struct as a forward declaration.
2702 // Then (if it is a definition) we go through and get debug info for all of
2703 // its members. Finally, we create a descriptor for the complete type (which
2704 // may refer to the forward decl if the struct is recursive) and replace all
2705 // uses of the forward declaration with the final definition.
2706 llvm::DICompositeType
*FwdDecl
= getOrCreateLimitedType(Ty
);
2708 const RecordDecl
*D
= RD
->getDefinition();
2709 if (!D
|| !D
->isCompleteDefinition())
2710 return {FwdDecl
, nullptr};
2712 if (const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
))
2713 CollectContainingType(CXXDecl
, FwdDecl
);
2715 // Push the struct on region stack.
2716 LexicalBlockStack
.emplace_back(&*FwdDecl
);
2717 RegionMap
[Ty
->getDecl()].reset(FwdDecl
);
2719 // Convert all the elements.
2720 SmallVector
<llvm::Metadata
*, 16> EltTys
;
2721 // what about nested types?
2723 // Note: The split of CXXDecl information here is intentional, the
2724 // gdb tests will depend on a certain ordering at printout. The debug
2725 // information offsets are still correct if we merge them all together
2727 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
);
2729 CollectCXXBases(CXXDecl
, DefUnit
, EltTys
, FwdDecl
);
2730 CollectVTableInfo(CXXDecl
, DefUnit
, EltTys
);
2733 // Collect data fields (including static variables and any initializers).
2734 CollectRecordFields(RD
, DefUnit
, EltTys
, FwdDecl
);
2736 CollectCXXMemberFunctions(CXXDecl
, DefUnit
, EltTys
, FwdDecl
);
2738 LexicalBlockStack
.pop_back();
2739 RegionMap
.erase(Ty
->getDecl());
2741 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
2742 DBuilder
.replaceArrays(FwdDecl
, Elements
);
2744 if (FwdDecl
->isTemporary())
2746 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl
));
2748 RegionMap
[Ty
->getDecl()].reset(FwdDecl
);
2750 if (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
)
2751 if (auto *PrefDI
= GetPreferredNameType(CXXDecl
, DefUnit
))
2752 return {FwdDecl
, PrefDI
};
2754 return {FwdDecl
, nullptr};
2757 llvm::DIType
*CGDebugInfo::CreateType(const ObjCObjectType
*Ty
,
2758 llvm::DIFile
*Unit
) {
2759 // Ignore protocols.
2760 return getOrCreateType(Ty
->getBaseType(), Unit
);
2763 llvm::DIType
*CGDebugInfo::CreateType(const ObjCTypeParamType
*Ty
,
2764 llvm::DIFile
*Unit
) {
2765 // Ignore protocols.
2766 SourceLocation Loc
= Ty
->getDecl()->getLocation();
2768 // Use Typedefs to represent ObjCTypeParamType.
2769 return DBuilder
.createTypedef(
2770 getOrCreateType(Ty
->getDecl()->getUnderlyingType(), Unit
),
2771 Ty
->getDecl()->getName(), getOrCreateFile(Loc
), getLineNumber(Loc
),
2772 getDeclContextDescriptor(Ty
->getDecl()));
2775 /// \return true if Getter has the default name for the property PD.
2776 static bool hasDefaultGetterName(const ObjCPropertyDecl
*PD
,
2777 const ObjCMethodDecl
*Getter
) {
2782 assert(Getter
->getDeclName().isObjCZeroArgSelector());
2783 return PD
->getName() ==
2784 Getter
->getDeclName().getObjCSelector().getNameForSlot(0);
2787 /// \return true if Setter has the default name for the property PD.
2788 static bool hasDefaultSetterName(const ObjCPropertyDecl
*PD
,
2789 const ObjCMethodDecl
*Setter
) {
2794 assert(Setter
->getDeclName().isObjCOneArgSelector());
2795 return SelectorTable::constructSetterName(PD
->getName()) ==
2796 Setter
->getDeclName().getObjCSelector().getNameForSlot(0);
2799 llvm::DIType
*CGDebugInfo::CreateType(const ObjCInterfaceType
*Ty
,
2800 llvm::DIFile
*Unit
) {
2801 ObjCInterfaceDecl
*ID
= Ty
->getDecl();
2805 // Return a forward declaration if this type was imported from a clang module,
2806 // and this is not the compile unit with the implementation of the type (which
2807 // may contain hidden ivars).
2808 if (DebugTypeExtRefs
&& ID
->isFromASTFile() && ID
->getDefinition() &&
2809 !ID
->getImplementation())
2810 return DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
2812 getDeclContextDescriptor(ID
), Unit
, 0);
2814 // Get overall information about the record type for the debug info.
2815 llvm::DIFile
*DefUnit
= getOrCreateFile(ID
->getLocation());
2816 unsigned Line
= getLineNumber(ID
->getLocation());
2818 static_cast<llvm::dwarf::SourceLanguage
>(TheCU
->getSourceLanguage());
2820 // If this is just a forward declaration return a special forward-declaration
2821 // debug type since we won't be able to lay out the entire type.
2822 ObjCInterfaceDecl
*Def
= ID
->getDefinition();
2823 if (!Def
|| !Def
->getImplementation()) {
2824 llvm::DIScope
*Mod
= getParentModuleOrNull(ID
);
2825 llvm::DIType
*FwdDecl
= DBuilder
.createReplaceableCompositeType(
2826 llvm::dwarf::DW_TAG_structure_type
, ID
->getName(), Mod
? Mod
: TheCU
,
2827 DefUnit
, Line
, RuntimeLang
);
2828 ObjCInterfaceCache
.push_back(ObjCInterfaceCacheEntry(Ty
, FwdDecl
, Unit
));
2832 return CreateTypeDefinition(Ty
, Unit
);
2835 llvm::DIModule
*CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod
,
2836 bool CreateSkeletonCU
) {
2837 // Use the Module pointer as the key into the cache. This is a
2838 // nullptr if the "Module" is a PCH, which is safe because we don't
2839 // support chained PCH debug info, so there can only be a single PCH.
2840 const Module
*M
= Mod
.getModuleOrNull();
2841 auto ModRef
= ModuleCache
.find(M
);
2842 if (ModRef
!= ModuleCache
.end())
2843 return cast
<llvm::DIModule
>(ModRef
->second
);
2845 // Macro definitions that were defined with "-D" on the command line.
2846 SmallString
<128> ConfigMacros
;
2848 llvm::raw_svector_ostream
OS(ConfigMacros
);
2849 const auto &PPOpts
= CGM
.getPreprocessorOpts();
2851 // Translate the macro definitions back into a command line.
2852 for (auto &M
: PPOpts
.Macros
) {
2855 const std::string
&Macro
= M
.first
;
2856 bool Undef
= M
.second
;
2857 OS
<< "\"-" << (Undef
? 'U' : 'D');
2858 for (char c
: Macro
)
2873 bool IsRootModule
= M
? !M
->Parent
: true;
2874 // When a module name is specified as -fmodule-name, that module gets a
2875 // clang::Module object, but it won't actually be built or imported; it will
2877 if (CreateSkeletonCU
&& IsRootModule
&& Mod
.getASTFile().empty() && M
)
2878 assert(StringRef(M
->Name
).startswith(CGM
.getLangOpts().ModuleName
) &&
2879 "clang module without ASTFile must be specified by -fmodule-name");
2881 // Return a StringRef to the remapped Path.
2882 auto RemapPath
= [this](StringRef Path
) -> std::string
{
2883 std::string Remapped
= remapDIPath(Path
);
2884 StringRef
Relative(Remapped
);
2885 StringRef CompDir
= TheCU
->getDirectory();
2886 if (Relative
.consume_front(CompDir
))
2887 Relative
.consume_front(llvm::sys::path::get_separator());
2889 return Relative
.str();
2892 if (CreateSkeletonCU
&& IsRootModule
&& !Mod
.getASTFile().empty()) {
2893 // PCH files don't have a signature field in the control block,
2894 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2895 // We use the lower 64 bits for debug info.
2897 uint64_t Signature
= 0;
2898 if (const auto &ModSig
= Mod
.getSignature())
2899 Signature
= ModSig
.truncatedValue();
2903 llvm::DIBuilder
DIB(CGM
.getModule());
2905 if (!llvm::sys::path::is_absolute(Mod
.getASTFile())) {
2906 if (CGM
.getHeaderSearchOpts().ModuleFileHomeIsCwd
)
2907 PCM
= getCurrentDirname();
2909 PCM
= Mod
.getPath();
2911 llvm::sys::path::append(PCM
, Mod
.getASTFile());
2912 DIB
.createCompileUnit(
2913 TheCU
->getSourceLanguage(),
2914 // TODO: Support "Source" from external AST providers?
2915 DIB
.createFile(Mod
.getModuleName(), TheCU
->getDirectory()),
2916 TheCU
->getProducer(), false, StringRef(), 0, RemapPath(PCM
),
2917 llvm::DICompileUnit::FullDebug
, Signature
);
2921 llvm::DIModule
*Parent
=
2922 IsRootModule
? nullptr
2923 : getOrCreateModuleRef(ASTSourceDescriptor(*M
->Parent
),
2925 std::string IncludePath
= Mod
.getPath().str();
2926 llvm::DIModule
*DIMod
=
2927 DBuilder
.createModule(Parent
, Mod
.getModuleName(), ConfigMacros
,
2928 RemapPath(IncludePath
));
2929 ModuleCache
[M
].reset(DIMod
);
2933 llvm::DIType
*CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType
*Ty
,
2934 llvm::DIFile
*Unit
) {
2935 ObjCInterfaceDecl
*ID
= Ty
->getDecl();
2936 llvm::DIFile
*DefUnit
= getOrCreateFile(ID
->getLocation());
2937 unsigned Line
= getLineNumber(ID
->getLocation());
2938 unsigned RuntimeLang
= TheCU
->getSourceLanguage();
2940 // Bit size, align and offset of the type.
2941 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
2942 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
2944 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
2945 if (ID
->getImplementation())
2946 Flags
|= llvm::DINode::FlagObjcClassComplete
;
2948 llvm::DIScope
*Mod
= getParentModuleOrNull(ID
);
2949 llvm::DICompositeType
*RealDecl
= DBuilder
.createStructType(
2950 Mod
? Mod
: Unit
, ID
->getName(), DefUnit
, Line
, Size
, Align
, Flags
,
2951 nullptr, llvm::DINodeArray(), RuntimeLang
);
2953 QualType
QTy(Ty
, 0);
2954 TypeCache
[QTy
.getAsOpaquePtr()].reset(RealDecl
);
2956 // Push the struct on region stack.
2957 LexicalBlockStack
.emplace_back(RealDecl
);
2958 RegionMap
[Ty
->getDecl()].reset(RealDecl
);
2960 // Convert all the elements.
2961 SmallVector
<llvm::Metadata
*, 16> EltTys
;
2963 ObjCInterfaceDecl
*SClass
= ID
->getSuperClass();
2965 llvm::DIType
*SClassTy
=
2966 getOrCreateType(CGM
.getContext().getObjCInterfaceType(SClass
), Unit
);
2970 llvm::DIType
*InhTag
= DBuilder
.createInheritance(RealDecl
, SClassTy
, 0, 0,
2971 llvm::DINode::FlagZero
);
2972 EltTys
.push_back(InhTag
);
2975 // Create entries for all of the properties.
2976 auto AddProperty
= [&](const ObjCPropertyDecl
*PD
) {
2977 SourceLocation Loc
= PD
->getLocation();
2978 llvm::DIFile
*PUnit
= getOrCreateFile(Loc
);
2979 unsigned PLine
= getLineNumber(Loc
);
2980 ObjCMethodDecl
*Getter
= PD
->getGetterMethodDecl();
2981 ObjCMethodDecl
*Setter
= PD
->getSetterMethodDecl();
2982 llvm::MDNode
*PropertyNode
= DBuilder
.createObjCProperty(
2983 PD
->getName(), PUnit
, PLine
,
2984 hasDefaultGetterName(PD
, Getter
) ? ""
2985 : getSelectorName(PD
->getGetterName()),
2986 hasDefaultSetterName(PD
, Setter
) ? ""
2987 : getSelectorName(PD
->getSetterName()),
2988 PD
->getPropertyAttributes(), getOrCreateType(PD
->getType(), PUnit
));
2989 EltTys
.push_back(PropertyNode
);
2992 // Use 'char' for the isClassProperty bit as DenseSet requires space for
2993 // empty/tombstone keys in the data type (and bool is too small for that).
2994 typedef std::pair
<char, const IdentifierInfo
*> IsClassAndIdent
;
2995 /// List of already emitted properties. Two distinct class and instance
2996 /// properties can share the same identifier (but not two instance
2997 /// properties or two class properties).
2998 llvm::DenseSet
<IsClassAndIdent
> PropertySet
;
2999 /// Returns the IsClassAndIdent key for the given property.
3000 auto GetIsClassAndIdent
= [](const ObjCPropertyDecl
*PD
) {
3001 return std::make_pair(PD
->isClassProperty(), PD
->getIdentifier());
3003 for (const ObjCCategoryDecl
*ClassExt
: ID
->known_extensions())
3004 for (auto *PD
: ClassExt
->properties()) {
3005 PropertySet
.insert(GetIsClassAndIdent(PD
));
3008 for (const auto *PD
: ID
->properties()) {
3009 // Don't emit duplicate metadata for properties that were already in a
3011 if (!PropertySet
.insert(GetIsClassAndIdent(PD
)).second
)
3017 const ASTRecordLayout
&RL
= CGM
.getContext().getASTObjCInterfaceLayout(ID
);
3018 unsigned FieldNo
= 0;
3019 for (ObjCIvarDecl
*Field
= ID
->all_declared_ivar_begin(); Field
;
3020 Field
= Field
->getNextIvar(), ++FieldNo
) {
3021 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
3025 StringRef FieldName
= Field
->getName();
3027 // Ignore unnamed fields.
3028 if (FieldName
.empty())
3031 // Get the location for the field.
3032 llvm::DIFile
*FieldDefUnit
= getOrCreateFile(Field
->getLocation());
3033 unsigned FieldLine
= getLineNumber(Field
->getLocation());
3034 QualType FType
= Field
->getType();
3035 uint64_t FieldSize
= 0;
3036 uint32_t FieldAlign
= 0;
3038 if (!FType
->isIncompleteArrayType()) {
3040 // Bit size, align and offset of the type.
3041 FieldSize
= Field
->isBitField()
3042 ? Field
->getBitWidthValue(CGM
.getContext())
3043 : CGM
.getContext().getTypeSize(FType
);
3044 FieldAlign
= getTypeAlignIfRequired(FType
, CGM
.getContext());
3047 uint64_t FieldOffset
;
3048 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
3049 // We don't know the runtime offset of an ivar if we're using the
3050 // non-fragile ABI. For bitfields, use the bit offset into the first
3051 // byte of storage of the bitfield. For other fields, use zero.
3052 if (Field
->isBitField()) {
3054 CGM
.getObjCRuntime().ComputeBitfieldBitOffset(CGM
, ID
, Field
);
3055 FieldOffset
%= CGM
.getContext().getCharWidth();
3060 FieldOffset
= RL
.getFieldOffset(FieldNo
);
3063 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3064 if (Field
->getAccessControl() == ObjCIvarDecl::Protected
)
3065 Flags
= llvm::DINode::FlagProtected
;
3066 else if (Field
->getAccessControl() == ObjCIvarDecl::Private
)
3067 Flags
= llvm::DINode::FlagPrivate
;
3068 else if (Field
->getAccessControl() == ObjCIvarDecl::Public
)
3069 Flags
= llvm::DINode::FlagPublic
;
3071 if (Field
->isBitField())
3072 Flags
|= llvm::DINode::FlagBitField
;
3074 llvm::MDNode
*PropertyNode
= nullptr;
3075 if (ObjCImplementationDecl
*ImpD
= ID
->getImplementation()) {
3076 if (ObjCPropertyImplDecl
*PImpD
=
3077 ImpD
->FindPropertyImplIvarDecl(Field
->getIdentifier())) {
3078 if (ObjCPropertyDecl
*PD
= PImpD
->getPropertyDecl()) {
3079 SourceLocation Loc
= PD
->getLocation();
3080 llvm::DIFile
*PUnit
= getOrCreateFile(Loc
);
3081 unsigned PLine
= getLineNumber(Loc
);
3082 ObjCMethodDecl
*Getter
= PImpD
->getGetterMethodDecl();
3083 ObjCMethodDecl
*Setter
= PImpD
->getSetterMethodDecl();
3084 PropertyNode
= DBuilder
.createObjCProperty(
3085 PD
->getName(), PUnit
, PLine
,
3086 hasDefaultGetterName(PD
, Getter
)
3088 : getSelectorName(PD
->getGetterName()),
3089 hasDefaultSetterName(PD
, Setter
)
3091 : getSelectorName(PD
->getSetterName()),
3092 PD
->getPropertyAttributes(),
3093 getOrCreateType(PD
->getType(), PUnit
));
3097 FieldTy
= DBuilder
.createObjCIVar(FieldName
, FieldDefUnit
, FieldLine
,
3098 FieldSize
, FieldAlign
, FieldOffset
, Flags
,
3099 FieldTy
, PropertyNode
);
3100 EltTys
.push_back(FieldTy
);
3103 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
3104 DBuilder
.replaceArrays(RealDecl
, Elements
);
3106 LexicalBlockStack
.pop_back();
3110 llvm::DIType
*CGDebugInfo::CreateType(const VectorType
*Ty
,
3111 llvm::DIFile
*Unit
) {
3112 if (Ty
->isExtVectorBoolType()) {
3113 // Boolean ext_vector_type(N) are special because their real element type
3114 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3115 // For now, we pretend the boolean vector were actually a vector of bytes
3116 // (where each byte represents 8 bits of the actual vector).
3117 // FIXME Debug info should actually represent this proper as a vector mask
3119 auto &Ctx
= CGM
.getContext();
3120 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3121 uint64_t NumVectorBytes
= Size
/ Ctx
.getCharWidth();
3123 // Construct the vector of 'char' type.
3124 QualType CharVecTy
=
3125 Ctx
.getVectorType(Ctx
.CharTy
, NumVectorBytes
, VectorKind::Generic
);
3126 return CreateType(CharVecTy
->getAs
<VectorType
>(), Unit
);
3129 llvm::DIType
*ElementTy
= getOrCreateType(Ty
->getElementType(), Unit
);
3130 int64_t Count
= Ty
->getNumElements();
3132 llvm::Metadata
*Subscript
;
3133 QualType
QTy(Ty
, 0);
3134 auto SizeExpr
= SizeExprCache
.find(QTy
);
3135 if (SizeExpr
!= SizeExprCache
.end())
3136 Subscript
= DBuilder
.getOrCreateSubrange(
3137 SizeExpr
->getSecond() /*count*/, nullptr /*lowerBound*/,
3138 nullptr /*upperBound*/, nullptr /*stride*/);
3141 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3142 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Count
? Count
: -1));
3143 Subscript
= DBuilder
.getOrCreateSubrange(
3144 CountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3145 nullptr /*stride*/);
3147 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
3149 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3150 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3152 return DBuilder
.createVectorType(Size
, Align
, ElementTy
, SubscriptArray
);
3155 llvm::DIType
*CGDebugInfo::CreateType(const ConstantMatrixType
*Ty
,
3156 llvm::DIFile
*Unit
) {
3157 // FIXME: Create another debug type for matrices
3158 // For the time being, it treats it like a nested ArrayType.
3160 llvm::DIType
*ElementTy
= getOrCreateType(Ty
->getElementType(), Unit
);
3161 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3162 uint32_t Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3164 // Create ranges for both dimensions.
3165 llvm::SmallVector
<llvm::Metadata
*, 2> Subscripts
;
3166 auto *ColumnCountNode
=
3167 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3168 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Ty
->getNumColumns()));
3169 auto *RowCountNode
=
3170 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3171 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Ty
->getNumRows()));
3172 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3173 ColumnCountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3174 nullptr /*stride*/));
3175 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3176 RowCountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3177 nullptr /*stride*/));
3178 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscripts
);
3179 return DBuilder
.createArrayType(Size
, Align
, ElementTy
, SubscriptArray
);
3182 llvm::DIType
*CGDebugInfo::CreateType(const ArrayType
*Ty
, llvm::DIFile
*Unit
) {
3186 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3187 if (const auto *VAT
= dyn_cast
<VariableArrayType
>(Ty
)) {
3189 Align
= getTypeAlignIfRequired(CGM
.getContext().getBaseElementType(VAT
),
3191 } else if (Ty
->isIncompleteArrayType()) {
3193 if (Ty
->getElementType()->isIncompleteType())
3196 Align
= getTypeAlignIfRequired(Ty
->getElementType(), CGM
.getContext());
3197 } else if (Ty
->isIncompleteType()) {
3201 // Size and align of the whole array, not the element type.
3202 Size
= CGM
.getContext().getTypeSize(Ty
);
3203 Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3206 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3207 // interior arrays, do we care? Why aren't nested arrays represented the
3208 // obvious/recursive way?
3209 SmallVector
<llvm::Metadata
*, 8> Subscripts
;
3210 QualType
EltTy(Ty
, 0);
3211 while ((Ty
= dyn_cast
<ArrayType
>(EltTy
))) {
3212 // If the number of elements is known, then count is that number. Otherwise,
3213 // it's -1. This allows us to represent a subrange with an array of 0
3214 // elements, like this:
3219 int64_t Count
= -1; // Count == -1 is an unbounded array.
3220 if (const auto *CAT
= dyn_cast
<ConstantArrayType
>(Ty
))
3221 Count
= CAT
->getSize().getZExtValue();
3222 else if (const auto *VAT
= dyn_cast
<VariableArrayType
>(Ty
)) {
3223 if (Expr
*Size
= VAT
->getSizeExpr()) {
3224 Expr::EvalResult Result
;
3225 if (Size
->EvaluateAsInt(Result
, CGM
.getContext()))
3226 Count
= Result
.Val
.getInt().getExtValue();
3230 auto SizeNode
= SizeExprCache
.find(EltTy
);
3231 if (SizeNode
!= SizeExprCache
.end())
3232 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3233 SizeNode
->getSecond() /*count*/, nullptr /*lowerBound*/,
3234 nullptr /*upperBound*/, nullptr /*stride*/));
3237 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3238 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Count
));
3239 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3240 CountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3241 nullptr /*stride*/));
3243 EltTy
= Ty
->getElementType();
3246 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscripts
);
3248 return DBuilder
.createArrayType(Size
, Align
, getOrCreateType(EltTy
, Unit
),
3252 llvm::DIType
*CGDebugInfo::CreateType(const LValueReferenceType
*Ty
,
3253 llvm::DIFile
*Unit
) {
3254 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type
, Ty
,
3255 Ty
->getPointeeType(), Unit
);
3258 llvm::DIType
*CGDebugInfo::CreateType(const RValueReferenceType
*Ty
,
3259 llvm::DIFile
*Unit
) {
3260 llvm::dwarf::Tag Tag
= llvm::dwarf::DW_TAG_rvalue_reference_type
;
3261 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3262 if (CGM
.getCodeGenOpts().DebugStrictDwarf
&&
3263 CGM
.getCodeGenOpts().DwarfVersion
< 4)
3264 Tag
= llvm::dwarf::DW_TAG_reference_type
;
3266 return CreatePointerLikeType(Tag
, Ty
, Ty
->getPointeeType(), Unit
);
3269 llvm::DIType
*CGDebugInfo::CreateType(const MemberPointerType
*Ty
,
3271 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3274 if (!Ty
->isIncompleteType()) {
3275 Size
= CGM
.getContext().getTypeSize(Ty
);
3277 // Set the MS inheritance model. There is no flag for the unspecified model.
3278 if (CGM
.getTarget().getCXXABI().isMicrosoft()) {
3279 switch (Ty
->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3280 case MSInheritanceModel::Single
:
3281 Flags
|= llvm::DINode::FlagSingleInheritance
;
3283 case MSInheritanceModel::Multiple
:
3284 Flags
|= llvm::DINode::FlagMultipleInheritance
;
3286 case MSInheritanceModel::Virtual
:
3287 Flags
|= llvm::DINode::FlagVirtualInheritance
;
3289 case MSInheritanceModel::Unspecified
:
3295 llvm::DIType
*ClassType
= getOrCreateType(QualType(Ty
->getClass(), 0), U
);
3296 if (Ty
->isMemberDataPointerType())
3297 return DBuilder
.createMemberPointerType(
3298 getOrCreateType(Ty
->getPointeeType(), U
), ClassType
, Size
, /*Align=*/0,
3301 const FunctionProtoType
*FPT
=
3302 Ty
->getPointeeType()->castAs
<FunctionProtoType
>();
3303 return DBuilder
.createMemberPointerType(
3304 getOrCreateInstanceMethodType(
3305 CXXMethodDecl::getThisType(FPT
, Ty
->getMostRecentCXXRecordDecl()),
3307 ClassType
, Size
, /*Align=*/0, Flags
);
3310 llvm::DIType
*CGDebugInfo::CreateType(const AtomicType
*Ty
, llvm::DIFile
*U
) {
3311 auto *FromTy
= getOrCreateType(Ty
->getValueType(), U
);
3312 return DBuilder
.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type
, FromTy
);
3315 llvm::DIType
*CGDebugInfo::CreateType(const PipeType
*Ty
, llvm::DIFile
*U
) {
3316 return getOrCreateType(Ty
->getElementType(), U
);
3319 llvm::DIType
*CGDebugInfo::CreateEnumType(const EnumType
*Ty
) {
3320 const EnumDecl
*ED
= Ty
->getDecl();
3324 if (!ED
->getTypeForDecl()->isIncompleteType()) {
3325 Size
= CGM
.getContext().getTypeSize(ED
->getTypeForDecl());
3326 Align
= getDeclAlignIfRequired(ED
, CGM
.getContext());
3329 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3331 bool isImportedFromModule
=
3332 DebugTypeExtRefs
&& ED
->isFromASTFile() && ED
->getDefinition();
3334 // If this is just a forward declaration, construct an appropriately
3335 // marked node and just return it.
3336 if (isImportedFromModule
|| !ED
->getDefinition()) {
3337 // Note that it is possible for enums to be created as part of
3338 // their own declcontext. In this case a FwdDecl will be created
3339 // twice. This doesn't cause a problem because both FwdDecls are
3340 // entered into the ReplaceMap: finalize() will replace the first
3341 // FwdDecl with the second and then replace the second with
3343 llvm::DIScope
*EDContext
= getDeclContextDescriptor(ED
);
3344 llvm::DIFile
*DefUnit
= getOrCreateFile(ED
->getLocation());
3345 llvm::TempDIScope
TmpContext(DBuilder
.createReplaceableCompositeType(
3346 llvm::dwarf::DW_TAG_enumeration_type
, "", TheCU
, DefUnit
, 0));
3348 unsigned Line
= getLineNumber(ED
->getLocation());
3349 StringRef EDName
= ED
->getName();
3350 llvm::DIType
*RetTy
= DBuilder
.createReplaceableCompositeType(
3351 llvm::dwarf::DW_TAG_enumeration_type
, EDName
, EDContext
, DefUnit
, Line
,
3352 0, Size
, Align
, llvm::DINode::FlagFwdDecl
, Identifier
);
3354 ReplaceMap
.emplace_back(
3355 std::piecewise_construct
, std::make_tuple(Ty
),
3356 std::make_tuple(static_cast<llvm::Metadata
*>(RetTy
)));
3360 return CreateTypeDefinition(Ty
);
3363 llvm::DIType
*CGDebugInfo::CreateTypeDefinition(const EnumType
*Ty
) {
3364 const EnumDecl
*ED
= Ty
->getDecl();
3367 if (!ED
->getTypeForDecl()->isIncompleteType()) {
3368 Size
= CGM
.getContext().getTypeSize(ED
->getTypeForDecl());
3369 Align
= getDeclAlignIfRequired(ED
, CGM
.getContext());
3372 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3374 SmallVector
<llvm::Metadata
*, 16> Enumerators
;
3375 ED
= ED
->getDefinition();
3376 for (const auto *Enum
: ED
->enumerators()) {
3377 Enumerators
.push_back(
3378 DBuilder
.createEnumerator(Enum
->getName(), Enum
->getInitVal()));
3381 // Return a CompositeType for the enum itself.
3382 llvm::DINodeArray EltArray
= DBuilder
.getOrCreateArray(Enumerators
);
3384 llvm::DIFile
*DefUnit
= getOrCreateFile(ED
->getLocation());
3385 unsigned Line
= getLineNumber(ED
->getLocation());
3386 llvm::DIScope
*EnumContext
= getDeclContextDescriptor(ED
);
3387 llvm::DIType
*ClassTy
= getOrCreateType(ED
->getIntegerType(), DefUnit
);
3388 return DBuilder
.createEnumerationType(EnumContext
, ED
->getName(), DefUnit
,
3389 Line
, Size
, Align
, EltArray
, ClassTy
,
3390 Identifier
, ED
->isScoped());
3393 llvm::DIMacro
*CGDebugInfo::CreateMacro(llvm::DIMacroFile
*Parent
,
3394 unsigned MType
, SourceLocation LineLoc
,
3395 StringRef Name
, StringRef Value
) {
3396 unsigned Line
= LineLoc
.isInvalid() ? 0 : getLineNumber(LineLoc
);
3397 return DBuilder
.createMacro(Parent
, Line
, MType
, Name
, Value
);
3400 llvm::DIMacroFile
*CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile
*Parent
,
3401 SourceLocation LineLoc
,
3402 SourceLocation FileLoc
) {
3403 llvm::DIFile
*FName
= getOrCreateFile(FileLoc
);
3404 unsigned Line
= LineLoc
.isInvalid() ? 0 : getLineNumber(LineLoc
);
3405 return DBuilder
.createTempMacroFile(Parent
, Line
, FName
);
3408 static QualType
UnwrapTypeForDebugInfo(QualType T
, const ASTContext
&C
) {
3411 Qualifiers InnerQuals
= T
.getLocalQualifiers();
3412 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3413 // that is already there.
3414 Quals
+= Qualifiers::removeCommonQualifiers(Quals
, InnerQuals
);
3415 Quals
+= InnerQuals
;
3417 switch (T
->getTypeClass()) {
3419 return C
.getQualifiedType(T
.getTypePtr(), Quals
);
3420 case Type::TemplateSpecialization
: {
3421 const auto *Spec
= cast
<TemplateSpecializationType
>(T
);
3422 if (Spec
->isTypeAlias())
3423 return C
.getQualifiedType(T
.getTypePtr(), Quals
);
3424 T
= Spec
->desugar();
3427 case Type::TypeOfExpr
:
3428 T
= cast
<TypeOfExprType
>(T
)->getUnderlyingExpr()->getType();
3431 T
= cast
<TypeOfType
>(T
)->getUnmodifiedType();
3433 case Type::Decltype
:
3434 T
= cast
<DecltypeType
>(T
)->getUnderlyingType();
3436 case Type::UnaryTransform
:
3437 T
= cast
<UnaryTransformType
>(T
)->getUnderlyingType();
3439 case Type::Attributed
:
3440 T
= cast
<AttributedType
>(T
)->getEquivalentType();
3442 case Type::BTFTagAttributed
:
3443 T
= cast
<BTFTagAttributedType
>(T
)->getWrappedType();
3445 case Type::Elaborated
:
3446 T
= cast
<ElaboratedType
>(T
)->getNamedType();
3449 T
= cast
<UsingType
>(T
)->getUnderlyingType();
3452 T
= cast
<ParenType
>(T
)->getInnerType();
3454 case Type::MacroQualified
:
3455 T
= cast
<MacroQualifiedType
>(T
)->getUnderlyingType();
3457 case Type::SubstTemplateTypeParm
:
3458 T
= cast
<SubstTemplateTypeParmType
>(T
)->getReplacementType();
3461 case Type::DeducedTemplateSpecialization
: {
3462 QualType DT
= cast
<DeducedType
>(T
)->getDeducedType();
3463 assert(!DT
.isNull() && "Undeduced types shouldn't reach here.");
3467 case Type::Adjusted
:
3469 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3470 T
= cast
<AdjustedType
>(T
)->getAdjustedType();
3474 assert(T
!= LastT
&& "Type unwrapping failed to unwrap!");
3479 llvm::DIType
*CGDebugInfo::getTypeOrNull(QualType Ty
) {
3480 assert(Ty
== UnwrapTypeForDebugInfo(Ty
, CGM
.getContext()));
3481 auto It
= TypeCache
.find(Ty
.getAsOpaquePtr());
3482 if (It
!= TypeCache
.end()) {
3483 // Verify that the debug info still exists.
3484 if (llvm::Metadata
*V
= It
->second
)
3485 return cast
<llvm::DIType
>(V
);
3491 void CGDebugInfo::completeTemplateDefinition(
3492 const ClassTemplateSpecializationDecl
&SD
) {
3493 completeUnusedClass(SD
);
3496 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl
&D
) {
3497 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
||
3501 completeClassData(&D
);
3502 // In case this type has no member function definitions being emitted, ensure
3504 RetainedTypes
.push_back(CGM
.getContext().getRecordType(&D
).getAsOpaquePtr());
3507 llvm::DIType
*CGDebugInfo::getOrCreateType(QualType Ty
, llvm::DIFile
*Unit
) {
3511 llvm::TimeTraceScope
TimeScope("DebugType", [&]() {
3513 llvm::raw_string_ostream
OS(Name
);
3514 Ty
.print(OS
, getPrintingPolicy());
3518 // Unwrap the type as needed for debug information.
3519 Ty
= UnwrapTypeForDebugInfo(Ty
, CGM
.getContext());
3521 if (auto *T
= getTypeOrNull(Ty
))
3524 llvm::DIType
*Res
= CreateTypeNode(Ty
, Unit
);
3525 void *TyPtr
= Ty
.getAsOpaquePtr();
3527 // And update the type cache.
3528 TypeCache
[TyPtr
].reset(Res
);
3533 llvm::DIModule
*CGDebugInfo::getParentModuleOrNull(const Decl
*D
) {
3534 // A forward declaration inside a module header does not belong to the module.
3535 if (isa
<RecordDecl
>(D
) && !cast
<RecordDecl
>(D
)->getDefinition())
3537 if (DebugTypeExtRefs
&& D
->isFromASTFile()) {
3538 // Record a reference to an imported clang module or precompiled header.
3539 auto *Reader
= CGM
.getContext().getExternalSource();
3540 auto Idx
= D
->getOwningModuleID();
3541 auto Info
= Reader
->getSourceDescriptor(Idx
);
3543 return getOrCreateModuleRef(*Info
, /*SkeletonCU=*/true);
3544 } else if (ClangModuleMap
) {
3545 // We are building a clang module or a precompiled header.
3547 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3548 // and it wouldn't be necessary to specify the parent scope
3549 // because the type is already unique by definition (it would look
3550 // like the output of -fno-standalone-debug). On the other hand,
3551 // the parent scope helps a consumer to quickly locate the object
3552 // file where the type's definition is located, so it might be
3553 // best to make this behavior a command line or debugger tuning
3555 if (Module
*M
= D
->getOwningModule()) {
3556 // This is a (sub-)module.
3557 auto Info
= ASTSourceDescriptor(*M
);
3558 return getOrCreateModuleRef(Info
, /*SkeletonCU=*/false);
3560 // This the precompiled header being built.
3561 return getOrCreateModuleRef(PCHDescriptor
, /*SkeletonCU=*/false);
3568 llvm::DIType
*CGDebugInfo::CreateTypeNode(QualType Ty
, llvm::DIFile
*Unit
) {
3569 // Handle qualifiers, which recursively handles what they refer to.
3570 if (Ty
.hasLocalQualifiers())
3571 return CreateQualifiedType(Ty
, Unit
);
3573 // Work out details of type.
3574 switch (Ty
->getTypeClass()) {
3575 #define TYPE(Class, Base)
3576 #define ABSTRACT_TYPE(Class, Base)
3577 #define NON_CANONICAL_TYPE(Class, Base)
3578 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3579 #include "clang/AST/TypeNodes.inc"
3580 llvm_unreachable("Dependent types cannot show up in debug information");
3582 case Type::ExtVector
:
3584 return CreateType(cast
<VectorType
>(Ty
), Unit
);
3585 case Type::ConstantMatrix
:
3586 return CreateType(cast
<ConstantMatrixType
>(Ty
), Unit
);
3587 case Type::ObjCObjectPointer
:
3588 return CreateType(cast
<ObjCObjectPointerType
>(Ty
), Unit
);
3589 case Type::ObjCObject
:
3590 return CreateType(cast
<ObjCObjectType
>(Ty
), Unit
);
3591 case Type::ObjCTypeParam
:
3592 return CreateType(cast
<ObjCTypeParamType
>(Ty
), Unit
);
3593 case Type::ObjCInterface
:
3594 return CreateType(cast
<ObjCInterfaceType
>(Ty
), Unit
);
3596 return CreateType(cast
<BuiltinType
>(Ty
));
3598 return CreateType(cast
<ComplexType
>(Ty
));
3600 return CreateType(cast
<PointerType
>(Ty
), Unit
);
3601 case Type::BlockPointer
:
3602 return CreateType(cast
<BlockPointerType
>(Ty
), Unit
);
3604 return CreateType(cast
<TypedefType
>(Ty
), Unit
);
3606 return CreateType(cast
<RecordType
>(Ty
));
3608 return CreateEnumType(cast
<EnumType
>(Ty
));
3609 case Type::FunctionProto
:
3610 case Type::FunctionNoProto
:
3611 return CreateType(cast
<FunctionType
>(Ty
), Unit
);
3612 case Type::ConstantArray
:
3613 case Type::VariableArray
:
3614 case Type::IncompleteArray
:
3615 return CreateType(cast
<ArrayType
>(Ty
), Unit
);
3617 case Type::LValueReference
:
3618 return CreateType(cast
<LValueReferenceType
>(Ty
), Unit
);
3619 case Type::RValueReference
:
3620 return CreateType(cast
<RValueReferenceType
>(Ty
), Unit
);
3622 case Type::MemberPointer
:
3623 return CreateType(cast
<MemberPointerType
>(Ty
), Unit
);
3626 return CreateType(cast
<AtomicType
>(Ty
), Unit
);
3629 return CreateType(cast
<BitIntType
>(Ty
));
3631 return CreateType(cast
<PipeType
>(Ty
), Unit
);
3633 case Type::TemplateSpecialization
:
3634 return CreateType(cast
<TemplateSpecializationType
>(Ty
), Unit
);
3637 case Type::Attributed
:
3638 case Type::BTFTagAttributed
:
3639 case Type::Adjusted
:
3641 case Type::DeducedTemplateSpecialization
:
3642 case Type::Elaborated
:
3645 case Type::MacroQualified
:
3646 case Type::SubstTemplateTypeParm
:
3647 case Type::TypeOfExpr
:
3649 case Type::Decltype
:
3650 case Type::UnaryTransform
:
3654 llvm_unreachable("type should have been unwrapped!");
3657 llvm::DICompositeType
*
3658 CGDebugInfo::getOrCreateLimitedType(const RecordType
*Ty
) {
3659 QualType
QTy(Ty
, 0);
3661 auto *T
= cast_or_null
<llvm::DICompositeType
>(getTypeOrNull(QTy
));
3663 // We may have cached a forward decl when we could have created
3664 // a non-forward decl. Go ahead and create a non-forward decl
3666 if (T
&& !T
->isForwardDecl())
3669 // Otherwise create the type.
3670 llvm::DICompositeType
*Res
= CreateLimitedType(Ty
);
3672 // Propagate members from the declaration to the definition
3673 // CreateType(const RecordType*) will overwrite this with the members in the
3674 // correct order if the full type is needed.
3675 DBuilder
.replaceArrays(Res
, T
? T
->getElements() : llvm::DINodeArray());
3677 // And update the type cache.
3678 TypeCache
[QTy
.getAsOpaquePtr()].reset(Res
);
3682 // TODO: Currently used for context chains when limiting debug info.
3683 llvm::DICompositeType
*CGDebugInfo::CreateLimitedType(const RecordType
*Ty
) {
3684 RecordDecl
*RD
= Ty
->getDecl();
3686 // Get overall information about the record type for the debug info.
3687 StringRef RDName
= getClassName(RD
);
3688 const SourceLocation Loc
= RD
->getLocation();
3689 llvm::DIFile
*DefUnit
= nullptr;
3691 if (Loc
.isValid()) {
3692 DefUnit
= getOrCreateFile(Loc
);
3693 Line
= getLineNumber(Loc
);
3696 llvm::DIScope
*RDContext
= getDeclContextDescriptor(RD
);
3698 // If we ended up creating the type during the context chain construction,
3699 // just return that.
3700 auto *T
= cast_or_null
<llvm::DICompositeType
>(
3701 getTypeOrNull(CGM
.getContext().getRecordType(RD
)));
3702 if (T
&& (!T
->isForwardDecl() || !RD
->getDefinition()))
3705 // If this is just a forward or incomplete declaration, construct an
3706 // appropriately marked node and just return it.
3707 const RecordDecl
*D
= RD
->getDefinition();
3708 if (!D
|| !D
->isCompleteDefinition())
3709 return getOrCreateRecordFwdDecl(Ty
, RDContext
);
3711 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3712 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3713 // struct or struct member, where it only increases alignment unless 'packed'
3714 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3716 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3718 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3720 // Explicitly record the calling convention and export symbols for C++
3722 auto Flags
= llvm::DINode::FlagZero
;
3723 if (auto CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
3724 if (CGM
.getCXXABI().getRecordArgABI(CXXRD
) == CGCXXABI::RAA_Indirect
)
3725 Flags
|= llvm::DINode::FlagTypePassByReference
;
3727 Flags
|= llvm::DINode::FlagTypePassByValue
;
3729 // Record if a C++ record is non-trivial type.
3730 if (!CXXRD
->isTrivial())
3731 Flags
|= llvm::DINode::FlagNonTrivial
;
3733 // Record exports it symbols to the containing structure.
3734 if (CXXRD
->isAnonymousStructOrUnion())
3735 Flags
|= llvm::DINode::FlagExportSymbols
;
3737 Flags
|= getAccessFlag(CXXRD
->getAccess(),
3738 dyn_cast
<CXXRecordDecl
>(CXXRD
->getDeclContext()));
3741 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
3742 llvm::DICompositeType
*RealDecl
= DBuilder
.createReplaceableCompositeType(
3743 getTagForRecord(RD
), RDName
, RDContext
, DefUnit
, Line
, 0, Size
, Align
,
3744 Flags
, Identifier
, Annotations
);
3746 // Elements of composite types usually have back to the type, creating
3747 // uniquing cycles. Distinct nodes are more efficient.
3748 switch (RealDecl
->getTag()) {
3750 llvm_unreachable("invalid composite type tag");
3752 case llvm::dwarf::DW_TAG_array_type
:
3753 case llvm::dwarf::DW_TAG_enumeration_type
:
3754 // Array elements and most enumeration elements don't have back references,
3755 // so they don't tend to be involved in uniquing cycles and there is some
3756 // chance of merging them when linking together two modules. Only make
3757 // them distinct if they are ODR-uniqued.
3758 if (Identifier
.empty())
3762 case llvm::dwarf::DW_TAG_structure_type
:
3763 case llvm::dwarf::DW_TAG_union_type
:
3764 case llvm::dwarf::DW_TAG_class_type
:
3765 // Immediately resolve to a distinct node.
3767 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl
));
3771 RegionMap
[Ty
->getDecl()].reset(RealDecl
);
3772 TypeCache
[QualType(Ty
, 0).getAsOpaquePtr()].reset(RealDecl
);
3774 if (const auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
3775 DBuilder
.replaceArrays(RealDecl
, llvm::DINodeArray(),
3776 CollectCXXTemplateParams(TSpecial
, DefUnit
));
3780 void CGDebugInfo::CollectContainingType(const CXXRecordDecl
*RD
,
3781 llvm::DICompositeType
*RealDecl
) {
3782 // A class's primary base or the class itself contains the vtable.
3783 llvm::DIType
*ContainingType
= nullptr;
3784 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
3785 if (const CXXRecordDecl
*PBase
= RL
.getPrimaryBase()) {
3786 // Seek non-virtual primary base root.
3788 const ASTRecordLayout
&BRL
= CGM
.getContext().getASTRecordLayout(PBase
);
3789 const CXXRecordDecl
*PBT
= BRL
.getPrimaryBase();
3790 if (PBT
&& !BRL
.isPrimaryBaseVirtual())
3795 ContainingType
= getOrCreateType(QualType(PBase
->getTypeForDecl(), 0),
3796 getOrCreateFile(RD
->getLocation()));
3797 } else if (RD
->isDynamicClass())
3798 ContainingType
= RealDecl
;
3800 DBuilder
.replaceVTableHolder(RealDecl
, ContainingType
);
3803 llvm::DIType
*CGDebugInfo::CreateMemberType(llvm::DIFile
*Unit
, QualType FType
,
3804 StringRef Name
, uint64_t *Offset
) {
3805 llvm::DIType
*FieldTy
= CGDebugInfo::getOrCreateType(FType
, Unit
);
3806 uint64_t FieldSize
= CGM
.getContext().getTypeSize(FType
);
3807 auto FieldAlign
= getTypeAlignIfRequired(FType
, CGM
.getContext());
3809 DBuilder
.createMemberType(Unit
, Name
, Unit
, 0, FieldSize
, FieldAlign
,
3810 *Offset
, llvm::DINode::FlagZero
, FieldTy
);
3811 *Offset
+= FieldSize
;
3815 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD
, llvm::DIFile
*Unit
,
3817 StringRef
&LinkageName
,
3818 llvm::DIScope
*&FDContext
,
3819 llvm::DINodeArray
&TParamsArray
,
3820 llvm::DINode::DIFlags
&Flags
) {
3821 const auto *FD
= cast
<FunctionDecl
>(GD
.getCanonicalDecl().getDecl());
3822 Name
= getFunctionName(FD
);
3823 // Use mangled name as linkage name for C/C++ functions.
3824 if (FD
->getType()->getAs
<FunctionProtoType
>())
3825 LinkageName
= CGM
.getMangledName(GD
);
3826 if (FD
->hasPrototype())
3827 Flags
|= llvm::DINode::FlagPrototyped
;
3828 // No need to replicate the linkage name if it isn't different from the
3829 // subprogram name, no need to have it at all unless coverage is enabled or
3830 // debug is set to more than just line tables or extra debug info is needed.
3831 if (LinkageName
== Name
||
3832 (CGM
.getCodeGenOpts().CoverageNotesFile
.empty() &&
3833 CGM
.getCodeGenOpts().CoverageDataFile
.empty() &&
3834 !CGM
.getCodeGenOpts().DebugInfoForProfiling
&&
3835 !CGM
.getCodeGenOpts().PseudoProbeForProfiling
&&
3836 DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
))
3837 LinkageName
= StringRef();
3839 // Emit the function scope in line tables only mode (if CodeView) to
3840 // differentiate between function names.
3841 if (CGM
.getCodeGenOpts().hasReducedDebugInfo() ||
3842 (DebugKind
== llvm::codegenoptions::DebugLineTablesOnly
&&
3843 CGM
.getCodeGenOpts().EmitCodeView
)) {
3844 if (const NamespaceDecl
*NSDecl
=
3845 dyn_cast_or_null
<NamespaceDecl
>(FD
->getDeclContext()))
3846 FDContext
= getOrCreateNamespace(NSDecl
);
3847 else if (const RecordDecl
*RDecl
=
3848 dyn_cast_or_null
<RecordDecl
>(FD
->getDeclContext())) {
3849 llvm::DIScope
*Mod
= getParentModuleOrNull(RDecl
);
3850 FDContext
= getContextDescriptor(RDecl
, Mod
? Mod
: TheCU
);
3853 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
3854 // Check if it is a noreturn-marked function
3855 if (FD
->isNoReturn())
3856 Flags
|= llvm::DINode::FlagNoReturn
;
3857 // Collect template parameters.
3858 TParamsArray
= CollectFunctionTemplateParams(FD
, Unit
);
3862 void CGDebugInfo::collectVarDeclProps(const VarDecl
*VD
, llvm::DIFile
*&Unit
,
3863 unsigned &LineNo
, QualType
&T
,
3864 StringRef
&Name
, StringRef
&LinkageName
,
3865 llvm::MDTuple
*&TemplateParameters
,
3866 llvm::DIScope
*&VDContext
) {
3867 Unit
= getOrCreateFile(VD
->getLocation());
3868 LineNo
= getLineNumber(VD
->getLocation());
3870 setLocation(VD
->getLocation());
3873 if (T
->isIncompleteArrayType()) {
3874 // CodeGen turns int[] into int[1] so we'll do the same here.
3875 llvm::APInt
ConstVal(32, 1);
3876 QualType ET
= CGM
.getContext().getAsArrayType(T
)->getElementType();
3878 T
= CGM
.getContext().getConstantArrayType(ET
, ConstVal
, nullptr,
3879 ArraySizeModifier::Normal
, 0);
3882 Name
= VD
->getName();
3883 if (VD
->getDeclContext() && !isa
<FunctionDecl
>(VD
->getDeclContext()) &&
3884 !isa
<ObjCMethodDecl
>(VD
->getDeclContext()))
3885 LinkageName
= CGM
.getMangledName(VD
);
3886 if (LinkageName
== Name
)
3887 LinkageName
= StringRef();
3889 if (isa
<VarTemplateSpecializationDecl
>(VD
)) {
3890 llvm::DINodeArray parameterNodes
= CollectVarTemplateParams(VD
, &*Unit
);
3891 TemplateParameters
= parameterNodes
.get();
3893 TemplateParameters
= nullptr;
3896 // Since we emit declarations (DW_AT_members) for static members, place the
3897 // definition of those static members in the namespace they were declared in
3898 // in the source code (the lexical decl context).
3899 // FIXME: Generalize this for even non-member global variables where the
3900 // declaration and definition may have different lexical decl contexts, once
3901 // we have support for emitting declarations of (non-member) global variables.
3902 const DeclContext
*DC
= VD
->isStaticDataMember() ? VD
->getLexicalDeclContext()
3903 : VD
->getDeclContext();
3904 // When a record type contains an in-line initialization of a static data
3905 // member, and the record type is marked as __declspec(dllexport), an implicit
3906 // definition of the member will be created in the record context. DWARF
3907 // doesn't seem to have a nice way to describe this in a form that consumers
3908 // are likely to understand, so fake the "normal" situation of a definition
3909 // outside the class by putting it in the global scope.
3911 DC
= CGM
.getContext().getTranslationUnitDecl();
3913 llvm::DIScope
*Mod
= getParentModuleOrNull(VD
);
3914 VDContext
= getContextDescriptor(cast
<Decl
>(DC
), Mod
? Mod
: TheCU
);
3917 llvm::DISubprogram
*CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD
,
3919 llvm::DINodeArray TParamsArray
;
3920 StringRef Name
, LinkageName
;
3921 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3922 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
3923 SourceLocation Loc
= GD
.getDecl()->getLocation();
3924 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
3925 llvm::DIScope
*DContext
= Unit
;
3926 unsigned Line
= getLineNumber(Loc
);
3927 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, DContext
, TParamsArray
,
3929 auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
3931 // Build function type.
3932 SmallVector
<QualType
, 16> ArgTypes
;
3933 for (const ParmVarDecl
*Parm
: FD
->parameters())
3934 ArgTypes
.push_back(Parm
->getType());
3936 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
3937 QualType FnType
= CGM
.getContext().getFunctionType(
3938 FD
->getReturnType(), ArgTypes
, FunctionProtoType::ExtProtoInfo(CC
));
3939 if (!FD
->isExternallyVisible())
3940 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
3941 if (CGM
.getLangOpts().Optimize
)
3942 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
3945 Flags
|= getCallSiteRelatedAttrs();
3946 SPFlags
|= llvm::DISubprogram::SPFlagDefinition
;
3947 return DBuilder
.createFunction(
3948 DContext
, Name
, LinkageName
, Unit
, Line
,
3949 getOrCreateFunctionType(GD
.getDecl(), FnType
, Unit
), 0, Flags
, SPFlags
,
3950 TParamsArray
.get(), getFunctionDeclaration(FD
));
3953 llvm::DISubprogram
*SP
= DBuilder
.createTempFunctionFwdDecl(
3954 DContext
, Name
, LinkageName
, Unit
, Line
,
3955 getOrCreateFunctionType(GD
.getDecl(), FnType
, Unit
), 0, Flags
, SPFlags
,
3956 TParamsArray
.get(), getFunctionDeclaration(FD
));
3957 const FunctionDecl
*CanonDecl
= FD
->getCanonicalDecl();
3958 FwdDeclReplaceMap
.emplace_back(std::piecewise_construct
,
3959 std::make_tuple(CanonDecl
),
3960 std::make_tuple(SP
));
3964 llvm::DISubprogram
*CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD
) {
3965 return getFunctionFwdDeclOrStub(GD
, /* Stub = */ false);
3968 llvm::DISubprogram
*CGDebugInfo::getFunctionStub(GlobalDecl GD
) {
3969 return getFunctionFwdDeclOrStub(GD
, /* Stub = */ true);
3972 llvm::DIGlobalVariable
*
3973 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl
*VD
) {
3975 StringRef Name
, LinkageName
;
3976 SourceLocation Loc
= VD
->getLocation();
3977 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
3978 llvm::DIScope
*DContext
= Unit
;
3979 unsigned Line
= getLineNumber(Loc
);
3980 llvm::MDTuple
*TemplateParameters
= nullptr;
3982 collectVarDeclProps(VD
, Unit
, Line
, T
, Name
, LinkageName
, TemplateParameters
,
3984 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
3985 auto *GV
= DBuilder
.createTempGlobalVariableFwdDecl(
3986 DContext
, Name
, LinkageName
, Unit
, Line
, getOrCreateType(T
, Unit
),
3987 !VD
->isExternallyVisible(), nullptr, TemplateParameters
, Align
);
3988 FwdDeclReplaceMap
.emplace_back(
3989 std::piecewise_construct
,
3990 std::make_tuple(cast
<VarDecl
>(VD
->getCanonicalDecl())),
3991 std::make_tuple(static_cast<llvm::Metadata
*>(GV
)));
3995 llvm::DINode
*CGDebugInfo::getDeclarationOrDefinition(const Decl
*D
) {
3996 // We only need a declaration (not a definition) of the type - so use whatever
3997 // we would otherwise do to get a type for a pointee. (forward declarations in
3998 // limited debug info, full definitions (if the type definition is available)
3999 // in unlimited debug info)
4000 if (const auto *TD
= dyn_cast
<TypeDecl
>(D
))
4001 return getOrCreateType(CGM
.getContext().getTypeDeclType(TD
),
4002 getOrCreateFile(TD
->getLocation()));
4003 auto I
= DeclCache
.find(D
->getCanonicalDecl());
4005 if (I
!= DeclCache
.end()) {
4007 if (auto *GVE
= dyn_cast_or_null
<llvm::DIGlobalVariableExpression
>(N
))
4008 return GVE
->getVariable();
4009 return cast
<llvm::DINode
>(N
);
4012 // Search imported declaration cache if it is already defined
4013 // as imported declaration.
4014 auto IE
= ImportedDeclCache
.find(D
->getCanonicalDecl());
4016 if (IE
!= ImportedDeclCache
.end()) {
4017 auto N
= IE
->second
;
4018 if (auto *GVE
= dyn_cast_or_null
<llvm::DIImportedEntity
>(N
))
4019 return cast
<llvm::DINode
>(GVE
);
4020 return dyn_cast_or_null
<llvm::DINode
>(N
);
4023 // No definition for now. Emit a forward definition that might be
4024 // merged with a potential upcoming definition.
4025 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
4026 return getFunctionForwardDeclaration(FD
);
4027 else if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
4028 return getGlobalVariableForwardDeclaration(VD
);
4033 llvm::DISubprogram
*CGDebugInfo::getFunctionDeclaration(const Decl
*D
) {
4034 if (!D
|| DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4037 const auto *FD
= dyn_cast
<FunctionDecl
>(D
);
4042 auto *S
= getDeclContextDescriptor(D
);
4044 auto MI
= SPCache
.find(FD
->getCanonicalDecl());
4045 if (MI
== SPCache
.end()) {
4046 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
->getCanonicalDecl())) {
4047 return CreateCXXMemberFunction(MD
, getOrCreateFile(MD
->getLocation()),
4048 cast
<llvm::DICompositeType
>(S
));
4051 if (MI
!= SPCache
.end()) {
4052 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(MI
->second
);
4053 if (SP
&& !SP
->isDefinition())
4057 for (auto *NextFD
: FD
->redecls()) {
4058 auto MI
= SPCache
.find(NextFD
->getCanonicalDecl());
4059 if (MI
!= SPCache
.end()) {
4060 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(MI
->second
);
4061 if (SP
&& !SP
->isDefinition())
4068 llvm::DISubprogram
*CGDebugInfo::getObjCMethodDeclaration(
4069 const Decl
*D
, llvm::DISubroutineType
*FnType
, unsigned LineNo
,
4070 llvm::DINode::DIFlags Flags
, llvm::DISubprogram::DISPFlags SPFlags
) {
4071 if (!D
|| DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4074 const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
);
4078 if (CGM
.getCodeGenOpts().DwarfVersion
< 5 && !OMD
->isDirectMethod())
4081 if (OMD
->isDirectMethod())
4082 SPFlags
|= llvm::DISubprogram::SPFlagObjCDirect
;
4084 // Starting with DWARF V5 method declarations are emitted as children of
4085 // the interface type.
4086 auto *ID
= dyn_cast_or_null
<ObjCInterfaceDecl
>(D
->getDeclContext());
4088 ID
= OMD
->getClassInterface();
4091 QualType
QTy(ID
->getTypeForDecl(), 0);
4092 auto It
= TypeCache
.find(QTy
.getAsOpaquePtr());
4093 if (It
== TypeCache
.end())
4095 auto *InterfaceType
= cast
<llvm::DICompositeType
>(It
->second
);
4096 llvm::DISubprogram
*FD
= DBuilder
.createFunction(
4097 InterfaceType
, getObjCMethodName(OMD
), StringRef(),
4098 InterfaceType
->getFile(), LineNo
, FnType
, LineNo
, Flags
, SPFlags
);
4099 DBuilder
.finalizeSubprogram(FD
);
4100 ObjCMethodCache
[ID
].push_back({FD
, OMD
->isDirectMethod()});
4104 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
4105 // implicit parameter "this".
4106 llvm::DISubroutineType
*CGDebugInfo::getOrCreateFunctionType(const Decl
*D
,
4109 // In CodeView, we emit the function types in line tables only because the
4110 // only way to distinguish between functions is by display name and type.
4111 if (!D
|| (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
&&
4112 !CGM
.getCodeGenOpts().EmitCodeView
))
4113 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4114 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4115 return DBuilder
.createSubroutineType(
4116 DBuilder
.getOrCreateTypeArray(std::nullopt
));
4118 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(D
))
4119 return getOrCreateMethodType(Method
, F
);
4121 const auto *FTy
= FnType
->getAs
<FunctionType
>();
4122 CallingConv CC
= FTy
? FTy
->getCallConv() : CallingConv::CC_C
;
4124 if (const auto *OMethod
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4125 // Add "self" and "_cmd"
4126 SmallVector
<llvm::Metadata
*, 16> Elts
;
4128 // First element is always return type. For 'void' functions it is NULL.
4129 QualType ResultTy
= OMethod
->getReturnType();
4131 // Replace the instancetype keyword with the actual type.
4132 if (ResultTy
== CGM
.getContext().getObjCInstanceType())
4133 ResultTy
= CGM
.getContext().getPointerType(
4134 QualType(OMethod
->getClassInterface()->getTypeForDecl(), 0));
4136 Elts
.push_back(getOrCreateType(ResultTy
, F
));
4137 // "self" pointer is always first argument.
4138 QualType SelfDeclTy
;
4139 if (auto *SelfDecl
= OMethod
->getSelfDecl())
4140 SelfDeclTy
= SelfDecl
->getType();
4141 else if (auto *FPT
= dyn_cast
<FunctionProtoType
>(FnType
))
4142 if (FPT
->getNumParams() > 1)
4143 SelfDeclTy
= FPT
->getParamType(0);
4144 if (!SelfDeclTy
.isNull())
4146 CreateSelfType(SelfDeclTy
, getOrCreateType(SelfDeclTy
, F
)));
4147 // "_cmd" pointer is always second argument.
4148 Elts
.push_back(DBuilder
.createArtificialType(
4149 getOrCreateType(CGM
.getContext().getObjCSelType(), F
)));
4150 // Get rest of the arguments.
4151 for (const auto *PI
: OMethod
->parameters())
4152 Elts
.push_back(getOrCreateType(PI
->getType(), F
));
4153 // Variadic methods need a special marker at the end of the type list.
4154 if (OMethod
->isVariadic())
4155 Elts
.push_back(DBuilder
.createUnspecifiedParameter());
4157 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(Elts
);
4158 return DBuilder
.createSubroutineType(EltTypeArray
, llvm::DINode::FlagZero
,
4162 // Handle variadic function types; they need an additional
4163 // unspecified parameter.
4164 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
4165 if (FD
->isVariadic()) {
4166 SmallVector
<llvm::Metadata
*, 16> EltTys
;
4167 EltTys
.push_back(getOrCreateType(FD
->getReturnType(), F
));
4168 if (const auto *FPT
= dyn_cast
<FunctionProtoType
>(FnType
))
4169 for (QualType ParamType
: FPT
->param_types())
4170 EltTys
.push_back(getOrCreateType(ParamType
, F
));
4171 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
4172 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(EltTys
);
4173 return DBuilder
.createSubroutineType(EltTypeArray
, llvm::DINode::FlagZero
,
4177 return cast
<llvm::DISubroutineType
>(getOrCreateType(FnType
, F
));
4181 CGDebugInfo::getFunctionType(const FunctionDecl
*FD
, QualType RetTy
,
4182 const SmallVectorImpl
<const VarDecl
*> &Args
) {
4183 CallingConv CC
= CallingConv::CC_C
;
4185 if (const auto *SrcFnTy
= FD
->getType()->getAs
<FunctionType
>())
4186 CC
= SrcFnTy
->getCallConv();
4187 SmallVector
<QualType
, 16> ArgTypes
;
4188 for (const VarDecl
*VD
: Args
)
4189 ArgTypes
.push_back(VD
->getType());
4190 return CGM
.getContext().getFunctionType(RetTy
, ArgTypes
,
4191 FunctionProtoType::ExtProtoInfo(CC
));
4194 void CGDebugInfo::emitFunctionStart(GlobalDecl GD
, SourceLocation Loc
,
4195 SourceLocation ScopeLoc
, QualType FnType
,
4196 llvm::Function
*Fn
, bool CurFuncIsThunk
) {
4198 StringRef LinkageName
;
4200 FnBeginRegionCount
.push_back(LexicalBlockStack
.size());
4202 const Decl
*D
= GD
.getDecl();
4203 bool HasDecl
= (D
!= nullptr);
4205 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4206 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
4207 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
4208 llvm::DIScope
*FDContext
= Unit
;
4209 llvm::DINodeArray TParamsArray
;
4211 // Use llvm function name.
4212 LinkageName
= Fn
->getName();
4213 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
4214 // If there is a subprogram for this function available then use it.
4215 auto FI
= SPCache
.find(FD
->getCanonicalDecl());
4216 if (FI
!= SPCache
.end()) {
4217 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(FI
->second
);
4218 if (SP
&& SP
->isDefinition()) {
4219 LexicalBlockStack
.emplace_back(SP
);
4220 RegionMap
[D
].reset(SP
);
4224 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, FDContext
,
4225 TParamsArray
, Flags
);
4226 } else if (const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4227 Name
= getObjCMethodName(OMD
);
4228 Flags
|= llvm::DINode::FlagPrototyped
;
4229 } else if (isa
<VarDecl
>(D
) &&
4230 GD
.getDynamicInitKind() != DynamicInitKind::NoStub
) {
4231 // This is a global initializer or atexit destructor for a global variable.
4232 Name
= getDynamicInitializerName(cast
<VarDecl
>(D
), GD
.getDynamicInitKind(),
4235 Name
= Fn
->getName();
4237 if (isa
<BlockDecl
>(D
))
4240 Flags
|= llvm::DINode::FlagPrototyped
;
4242 if (Name
.startswith("\01"))
4243 Name
= Name
.substr(1);
4245 assert((!D
|| !isa
<VarDecl
>(D
) ||
4246 GD
.getDynamicInitKind() != DynamicInitKind::NoStub
) &&
4247 "Unexpected DynamicInitKind !");
4249 if (!HasDecl
|| D
->isImplicit() || D
->hasAttr
<ArtificialAttr
>() ||
4250 isa
<VarDecl
>(D
) || isa
<CapturedDecl
>(D
)) {
4251 Flags
|= llvm::DINode::FlagArtificial
;
4252 // Artificial functions should not silently reuse CurLoc.
4253 CurLoc
= SourceLocation();
4257 Flags
|= llvm::DINode::FlagThunk
;
4259 if (Fn
->hasLocalLinkage())
4260 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
4261 if (CGM
.getLangOpts().Optimize
)
4262 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
4264 llvm::DINode::DIFlags FlagsForDef
= Flags
| getCallSiteRelatedAttrs();
4265 llvm::DISubprogram::DISPFlags SPFlagsForDef
=
4266 SPFlags
| llvm::DISubprogram::SPFlagDefinition
;
4268 const unsigned LineNo
= getLineNumber(Loc
.isValid() ? Loc
: CurLoc
);
4269 unsigned ScopeLine
= getLineNumber(ScopeLoc
);
4270 llvm::DISubroutineType
*DIFnType
= getOrCreateFunctionType(D
, FnType
, Unit
);
4271 llvm::DISubprogram
*Decl
= nullptr;
4272 llvm::DINodeArray Annotations
= nullptr;
4274 Decl
= isa
<ObjCMethodDecl
>(D
)
4275 ? getObjCMethodDeclaration(D
, DIFnType
, LineNo
, Flags
, SPFlags
)
4276 : getFunctionDeclaration(D
);
4277 Annotations
= CollectBTFDeclTagAnnotations(D
);
4280 // FIXME: The function declaration we're constructing here is mostly reusing
4281 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4282 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4283 // all subprograms instead of the actual context since subprogram definitions
4284 // are emitted as CU level entities by the backend.
4285 llvm::DISubprogram
*SP
= DBuilder
.createFunction(
4286 FDContext
, Name
, LinkageName
, Unit
, LineNo
, DIFnType
, ScopeLine
,
4287 FlagsForDef
, SPFlagsForDef
, TParamsArray
.get(), Decl
, nullptr,
4289 Fn
->setSubprogram(SP
);
4290 // We might get here with a VarDecl in the case we're generating
4291 // code for the initialization of globals. Do not record these decls
4292 // as they will overwrite the actual VarDecl Decl in the cache.
4293 if (HasDecl
&& isa
<FunctionDecl
>(D
))
4294 DeclCache
[D
->getCanonicalDecl()].reset(SP
);
4296 // Push the function onto the lexical block stack.
4297 LexicalBlockStack
.emplace_back(SP
);
4300 RegionMap
[D
].reset(SP
);
4303 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD
, SourceLocation Loc
,
4304 QualType FnType
, llvm::Function
*Fn
) {
4306 StringRef LinkageName
;
4308 const Decl
*D
= GD
.getDecl();
4312 llvm::TimeTraceScope
TimeScope("DebugFunction", [&]() {
4313 return GetName(D
, true);
4316 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4317 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
4318 bool IsDeclForCallSite
= Fn
? true : false;
4319 llvm::DIScope
*FDContext
=
4320 IsDeclForCallSite
? Unit
: getDeclContextDescriptor(D
);
4321 llvm::DINodeArray TParamsArray
;
4322 if (isa
<FunctionDecl
>(D
)) {
4323 // If there is a DISubprogram for this function available then use it.
4324 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, FDContext
,
4325 TParamsArray
, Flags
);
4326 } else if (const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4327 Name
= getObjCMethodName(OMD
);
4328 Flags
|= llvm::DINode::FlagPrototyped
;
4330 llvm_unreachable("not a function or ObjC method");
4332 if (!Name
.empty() && Name
[0] == '\01')
4333 Name
= Name
.substr(1);
4335 if (D
->isImplicit()) {
4336 Flags
|= llvm::DINode::FlagArtificial
;
4337 // Artificial functions without a location should not silently reuse CurLoc.
4338 if (Loc
.isInvalid())
4339 CurLoc
= SourceLocation();
4341 unsigned LineNo
= getLineNumber(Loc
);
4342 unsigned ScopeLine
= 0;
4343 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
4344 if (CGM
.getLangOpts().Optimize
)
4345 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
4347 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
4348 llvm::DISubroutineType
*STy
= getOrCreateFunctionType(D
, FnType
, Unit
);
4349 llvm::DISubprogram
*SP
= DBuilder
.createFunction(
4350 FDContext
, Name
, LinkageName
, Unit
, LineNo
, STy
, ScopeLine
, Flags
,
4351 SPFlags
, TParamsArray
.get(), nullptr, nullptr, Annotations
);
4353 // Preserve btf_decl_tag attributes for parameters of extern functions
4354 // for BPF target. The parameters created in this loop are attached as
4355 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4356 if (IsDeclForCallSite
&& CGM
.getTarget().getTriple().isBPF()) {
4357 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
4358 llvm::DITypeRefArray ParamTypes
= STy
->getTypeArray();
4360 for (ParmVarDecl
*PD
: FD
->parameters()) {
4361 llvm::DINodeArray ParamAnnotations
= CollectBTFDeclTagAnnotations(PD
);
4362 DBuilder
.createParameterVariable(
4363 SP
, PD
->getName(), ArgNo
, Unit
, LineNo
, ParamTypes
[ArgNo
], true,
4364 llvm::DINode::FlagZero
, ParamAnnotations
);
4370 if (IsDeclForCallSite
)
4371 Fn
->setSubprogram(SP
);
4373 DBuilder
.finalizeSubprogram(SP
);
4376 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase
*CallOrInvoke
,
4377 QualType CalleeType
,
4378 const FunctionDecl
*CalleeDecl
) {
4381 auto *Func
= CallOrInvoke
->getCalledFunction();
4384 if (Func
->getSubprogram())
4387 // Do not emit a declaration subprogram for a function with nodebug
4388 // attribute, or if call site info isn't required.
4389 if (CalleeDecl
->hasAttr
<NoDebugAttr
>() ||
4390 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero
)
4393 // If there is no DISubprogram attached to the function being called,
4394 // create the one describing the function in order to have complete
4395 // call site debug info.
4396 if (!CalleeDecl
->isStatic() && !CalleeDecl
->isInlined())
4397 EmitFunctionDecl(CalleeDecl
, CalleeDecl
->getLocation(), CalleeType
, Func
);
4400 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy
&Builder
, GlobalDecl GD
) {
4401 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4402 // If there is a subprogram for this function available then use it.
4403 auto FI
= SPCache
.find(FD
->getCanonicalDecl());
4404 llvm::DISubprogram
*SP
= nullptr;
4405 if (FI
!= SPCache
.end())
4406 SP
= dyn_cast_or_null
<llvm::DISubprogram
>(FI
->second
);
4407 if (!SP
|| !SP
->isDefinition())
4408 SP
= getFunctionStub(GD
);
4409 FnBeginRegionCount
.push_back(LexicalBlockStack
.size());
4410 LexicalBlockStack
.emplace_back(SP
);
4411 setInlinedAt(Builder
.getCurrentDebugLocation());
4412 EmitLocation(Builder
, FD
->getLocation());
4415 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy
&Builder
) {
4416 assert(CurInlinedAt
&& "unbalanced inline scope stack");
4417 EmitFunctionEnd(Builder
, nullptr);
4418 setInlinedAt(llvm::DebugLoc(CurInlinedAt
).getInlinedAt());
4421 void CGDebugInfo::EmitLocation(CGBuilderTy
&Builder
, SourceLocation Loc
) {
4422 // Update our current location
4425 if (CurLoc
.isInvalid() || CurLoc
.isMacroID() || LexicalBlockStack
.empty())
4428 llvm::MDNode
*Scope
= LexicalBlockStack
.back();
4429 Builder
.SetCurrentDebugLocation(
4430 llvm::DILocation::get(CGM
.getLLVMContext(), getLineNumber(CurLoc
),
4431 getColumnNumber(CurLoc
), Scope
, CurInlinedAt
));
4434 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc
) {
4435 llvm::MDNode
*Back
= nullptr;
4436 if (!LexicalBlockStack
.empty())
4437 Back
= LexicalBlockStack
.back().get();
4438 LexicalBlockStack
.emplace_back(DBuilder
.createLexicalBlock(
4439 cast
<llvm::DIScope
>(Back
), getOrCreateFile(CurLoc
), getLineNumber(CurLoc
),
4440 getColumnNumber(CurLoc
)));
4443 void CGDebugInfo::AppendAddressSpaceXDeref(
4444 unsigned AddressSpace
, SmallVectorImpl
<uint64_t> &Expr
) const {
4445 std::optional
<unsigned> DWARFAddressSpace
=
4446 CGM
.getTarget().getDWARFAddressSpace(AddressSpace
);
4447 if (!DWARFAddressSpace
)
4450 Expr
.push_back(llvm::dwarf::DW_OP_constu
);
4451 Expr
.push_back(*DWARFAddressSpace
);
4452 Expr
.push_back(llvm::dwarf::DW_OP_swap
);
4453 Expr
.push_back(llvm::dwarf::DW_OP_xderef
);
4456 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy
&Builder
,
4457 SourceLocation Loc
) {
4458 // Set our current location.
4461 // Emit a line table change for the current location inside the new scope.
4462 Builder
.SetCurrentDebugLocation(llvm::DILocation::get(
4463 CGM
.getLLVMContext(), getLineNumber(Loc
), getColumnNumber(Loc
),
4464 LexicalBlockStack
.back(), CurInlinedAt
));
4466 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4469 // Create a new lexical block and push it on the stack.
4470 CreateLexicalBlock(Loc
);
4473 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy
&Builder
,
4474 SourceLocation Loc
) {
4475 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4477 // Provide an entry in the line table for the end of the block.
4478 EmitLocation(Builder
, Loc
);
4480 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4483 LexicalBlockStack
.pop_back();
4486 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy
&Builder
, llvm::Function
*Fn
) {
4487 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4488 unsigned RCount
= FnBeginRegionCount
.back();
4489 assert(RCount
<= LexicalBlockStack
.size() && "Region stack mismatch");
4491 // Pop all regions for this function.
4492 while (LexicalBlockStack
.size() != RCount
) {
4493 // Provide an entry in the line table for the end of the block.
4494 EmitLocation(Builder
, CurLoc
);
4495 LexicalBlockStack
.pop_back();
4497 FnBeginRegionCount
.pop_back();
4499 if (Fn
&& Fn
->getSubprogram())
4500 DBuilder
.finalizeSubprogram(Fn
->getSubprogram());
4503 CGDebugInfo::BlockByRefType
4504 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl
*VD
,
4505 uint64_t *XOffset
) {
4506 SmallVector
<llvm::Metadata
*, 5> EltTys
;
4508 uint64_t FieldSize
, FieldOffset
;
4509 uint32_t FieldAlign
;
4511 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
4512 QualType Type
= VD
->getType();
4515 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4516 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
4517 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__forwarding", &FieldOffset
));
4518 FType
= CGM
.getContext().IntTy
;
4519 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
4520 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__size", &FieldOffset
));
4522 bool HasCopyAndDispose
= CGM
.getContext().BlockRequiresCopying(Type
, VD
);
4523 if (HasCopyAndDispose
) {
4524 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4526 CreateMemberType(Unit
, FType
, "__copy_helper", &FieldOffset
));
4528 CreateMemberType(Unit
, FType
, "__destroy_helper", &FieldOffset
));
4530 bool HasByrefExtendedLayout
;
4531 Qualifiers::ObjCLifetime Lifetime
;
4532 if (CGM
.getContext().getByrefLifetime(Type
, Lifetime
,
4533 HasByrefExtendedLayout
) &&
4534 HasByrefExtendedLayout
) {
4535 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4537 CreateMemberType(Unit
, FType
, "__byref_variable_layout", &FieldOffset
));
4540 CharUnits Align
= CGM
.getContext().getDeclAlign(VD
);
4541 if (Align
> CGM
.getContext().toCharUnitsFromBits(
4542 CGM
.getTarget().getPointerAlign(LangAS::Default
))) {
4543 CharUnits FieldOffsetInBytes
=
4544 CGM
.getContext().toCharUnitsFromBits(FieldOffset
);
4545 CharUnits AlignedOffsetInBytes
= FieldOffsetInBytes
.alignTo(Align
);
4546 CharUnits NumPaddingBytes
= AlignedOffsetInBytes
- FieldOffsetInBytes
;
4548 if (NumPaddingBytes
.isPositive()) {
4549 llvm::APInt
pad(32, NumPaddingBytes
.getQuantity());
4550 FType
= CGM
.getContext().getConstantArrayType(
4551 CGM
.getContext().CharTy
, pad
, nullptr, ArraySizeModifier::Normal
, 0);
4552 EltTys
.push_back(CreateMemberType(Unit
, FType
, "", &FieldOffset
));
4557 llvm::DIType
*WrappedTy
= getOrCreateType(FType
, Unit
);
4558 FieldSize
= CGM
.getContext().getTypeSize(FType
);
4559 FieldAlign
= CGM
.getContext().toBits(Align
);
4561 *XOffset
= FieldOffset
;
4562 llvm::DIType
*FieldTy
= DBuilder
.createMemberType(
4563 Unit
, VD
->getName(), Unit
, 0, FieldSize
, FieldAlign
, FieldOffset
,
4564 llvm::DINode::FlagZero
, WrappedTy
);
4565 EltTys
.push_back(FieldTy
);
4566 FieldOffset
+= FieldSize
;
4568 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
4569 return {DBuilder
.createStructType(Unit
, "", Unit
, 0, FieldOffset
, 0,
4570 llvm::DINode::FlagZero
, nullptr, Elements
),
4574 llvm::DILocalVariable
*CGDebugInfo::EmitDeclare(const VarDecl
*VD
,
4575 llvm::Value
*Storage
,
4576 std::optional
<unsigned> ArgNo
,
4577 CGBuilderTy
&Builder
,
4578 const bool UsePointerValue
) {
4579 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4580 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4581 if (VD
->hasAttr
<NoDebugAttr
>())
4585 VD
->isImplicit() || (isa
<Decl
>(VD
->getDeclContext()) &&
4586 cast
<Decl
>(VD
->getDeclContext())->isImplicit());
4587 llvm::DIFile
*Unit
= nullptr;
4589 Unit
= getOrCreateFile(VD
->getLocation());
4591 uint64_t XOffset
= 0;
4592 if (VD
->hasAttr
<BlocksAttr
>())
4593 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
).WrappedType
;
4595 Ty
= getOrCreateType(VD
->getType(), Unit
);
4597 // If there is no debug info for this type then do not emit debug info
4598 // for this variable.
4602 // Get location information.
4604 unsigned Column
= 0;
4606 Line
= getLineNumber(VD
->getLocation());
4607 Column
= getColumnNumber(VD
->getLocation());
4609 SmallVector
<uint64_t, 13> Expr
;
4610 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4611 if (VD
->isImplicit())
4612 Flags
|= llvm::DINode::FlagArtificial
;
4614 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
4616 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(VD
->getType());
4617 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
4619 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4620 // object pointer flag.
4621 if (const auto *IPD
= dyn_cast
<ImplicitParamDecl
>(VD
)) {
4622 if (IPD
->getParameterKind() == ImplicitParamDecl::CXXThis
||
4623 IPD
->getParameterKind() == ImplicitParamDecl::ObjCSelf
)
4624 Flags
|= llvm::DINode::FlagObjectPointer
;
4627 // Note: Older versions of clang used to emit byval references with an extra
4628 // DW_OP_deref, because they referenced the IR arg directly instead of
4629 // referencing an alloca. Newer versions of LLVM don't treat allocas
4630 // differently from other function arguments when used in a dbg.declare.
4631 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4632 StringRef Name
= VD
->getName();
4633 if (!Name
.empty()) {
4634 // __block vars are stored on the heap if they are captured by a block that
4635 // can escape the local scope.
4636 if (VD
->isEscapingByref()) {
4637 // Here, we need an offset *into* the alloca.
4638 CharUnits offset
= CharUnits::fromQuantity(32);
4639 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4640 // offset of __forwarding field
4641 offset
= CGM
.getContext().toCharUnitsFromBits(
4642 CGM
.getTarget().getPointerWidth(LangAS::Default
));
4643 Expr
.push_back(offset
.getQuantity());
4644 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4645 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4646 // offset of x field
4647 offset
= CGM
.getContext().toCharUnitsFromBits(XOffset
);
4648 Expr
.push_back(offset
.getQuantity());
4650 } else if (const auto *RT
= dyn_cast
<RecordType
>(VD
->getType())) {
4651 // If VD is an anonymous union then Storage represents value for
4652 // all union fields.
4653 const RecordDecl
*RD
= RT
->getDecl();
4654 if (RD
->isUnion() && RD
->isAnonymousStructOrUnion()) {
4655 // GDB has trouble finding local variables in anonymous unions, so we emit
4656 // artificial local variables for each of the members.
4658 // FIXME: Remove this code as soon as GDB supports this.
4659 // The debug info verifier in LLVM operates based on the assumption that a
4660 // variable has the same size as its storage and we had to disable the
4661 // check for artificial variables.
4662 for (const auto *Field
: RD
->fields()) {
4663 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
4664 StringRef FieldName
= Field
->getName();
4666 // Ignore unnamed fields. Do not ignore unnamed records.
4667 if (FieldName
.empty() && !isa
<RecordType
>(Field
->getType()))
4670 // Use VarDecl's Tag, Scope and Line number.
4671 auto FieldAlign
= getDeclAlignIfRequired(Field
, CGM
.getContext());
4672 auto *D
= DBuilder
.createAutoVariable(
4673 Scope
, FieldName
, Unit
, Line
, FieldTy
, CGM
.getLangOpts().Optimize
,
4674 Flags
| llvm::DINode::FlagArtificial
, FieldAlign
);
4676 // Insert an llvm.dbg.declare into the current block.
4677 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4678 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4681 Builder
.GetInsertBlock());
4686 // Clang stores the sret pointer provided by the caller in a static alloca.
4687 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4688 // the address of the variable.
4689 if (UsePointerValue
) {
4690 assert(!llvm::is_contained(Expr
, llvm::dwarf::DW_OP_deref
) &&
4691 "Debug info already contains DW_OP_deref.");
4692 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4695 // Create the descriptor for the variable.
4696 llvm::DILocalVariable
*D
= nullptr;
4698 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(VD
);
4699 D
= DBuilder
.createParameterVariable(Scope
, Name
, *ArgNo
, Unit
, Line
, Ty
,
4700 CGM
.getLangOpts().Optimize
, Flags
,
4703 // For normal local variable, we will try to find out whether 'VD' is the
4704 // copy parameter of coroutine.
4705 // If yes, we are going to use DIVariable of the origin parameter instead
4706 // of creating the new one.
4707 // If no, it might be a normal alloc, we just create a new one for it.
4709 // Check whether the VD is move parameters.
4710 auto RemapCoroArgToLocalVar
= [&]() -> llvm::DILocalVariable
* {
4711 // The scope of parameter and move-parameter should be distinct
4713 if (!isa
<llvm::DISubprogram
>(Scope
) || !Scope
->isDistinct())
4716 auto Iter
= llvm::find_if(CoroutineParameterMappings
, [&](auto &Pair
) {
4717 Stmt
*StmtPtr
= const_cast<Stmt
*>(Pair
.second
);
4718 if (DeclStmt
*DeclStmtPtr
= dyn_cast
<DeclStmt
>(StmtPtr
)) {
4719 DeclGroupRef DeclGroup
= DeclStmtPtr
->getDeclGroup();
4720 Decl
*Decl
= DeclGroup
.getSingleDecl();
4721 if (VD
== dyn_cast_or_null
<VarDecl
>(Decl
))
4727 if (Iter
!= CoroutineParameterMappings
.end()) {
4728 ParmVarDecl
*PD
= const_cast<ParmVarDecl
*>(Iter
->first
);
4729 auto Iter2
= llvm::find_if(ParamDbgMappings
, [&](auto &DbgPair
) {
4730 return DbgPair
.first
== PD
&& DbgPair
.second
->getScope() == Scope
;
4732 if (Iter2
!= ParamDbgMappings
.end())
4733 return const_cast<llvm::DILocalVariable
*>(Iter2
->second
);
4738 // If we couldn't find a move param DIVariable, create a new one.
4739 D
= RemapCoroArgToLocalVar();
4740 // Or we will create a new DIVariable for this Decl if D dose not exists.
4742 D
= DBuilder
.createAutoVariable(Scope
, Name
, Unit
, Line
, Ty
,
4743 CGM
.getLangOpts().Optimize
, Flags
, Align
);
4745 // Insert an llvm.dbg.declare into the current block.
4746 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4747 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4748 Column
, Scope
, CurInlinedAt
),
4749 Builder
.GetInsertBlock());
4754 llvm::DIType
*CGDebugInfo::CreateBindingDeclType(const BindingDecl
*BD
) {
4755 llvm::DIFile
*Unit
= getOrCreateFile(BD
->getLocation());
4757 // If the declaration is bound to a bitfield struct field, its type may have a
4758 // size that is different from its deduced declaration type's.
4759 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BD
->getBinding())) {
4760 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl())) {
4761 if (FD
->isBitField()) {
4762 ASTContext
&Context
= CGM
.getContext();
4763 const CGRecordLayout
&RL
=
4764 CGM
.getTypes().getCGRecordLayout(FD
->getParent());
4765 const CGBitFieldInfo
&Info
= RL
.getBitFieldInfo(FD
);
4767 // Find an integer type with the same bitwidth as the bitfield size. If
4768 // no suitable type is present in the target, give up on producing debug
4769 // information as it would be wrong. It is certainly possible to produce
4770 // correct debug info, but the logic isn't currently implemented.
4771 uint64_t BitfieldSizeInBits
= Info
.Size
;
4773 Context
.getIntTypeForBitwidth(BitfieldSizeInBits
, Info
.IsSigned
);
4776 Qualifiers Quals
= BD
->getType().getQualifiers();
4777 QualType FinalTy
= Context
.getQualifiedType(IntTy
, Quals
);
4778 llvm::DIType
*Ty
= getOrCreateType(FinalTy
, Unit
);
4785 return getOrCreateType(BD
->getType(), Unit
);
4788 llvm::DILocalVariable
*CGDebugInfo::EmitDeclare(const BindingDecl
*BD
,
4789 llvm::Value
*Storage
,
4790 std::optional
<unsigned> ArgNo
,
4791 CGBuilderTy
&Builder
,
4792 const bool UsePointerValue
) {
4793 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4794 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4795 if (BD
->hasAttr
<NoDebugAttr
>())
4798 // Skip the tuple like case, we don't handle that here
4799 if (isa
<DeclRefExpr
>(BD
->getBinding()))
4802 llvm::DIType
*Ty
= CreateBindingDeclType(BD
);
4804 // If there is no debug info for this type then do not emit debug info
4805 // for this variable.
4809 auto Align
= getDeclAlignIfRequired(BD
, CGM
.getContext());
4810 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(BD
->getType());
4812 SmallVector
<uint64_t, 3> Expr
;
4813 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
4815 // Clang stores the sret pointer provided by the caller in a static alloca.
4816 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4817 // the address of the variable.
4818 if (UsePointerValue
) {
4819 assert(!llvm::is_contained(Expr
, llvm::dwarf::DW_OP_deref
) &&
4820 "Debug info already contains DW_OP_deref.");
4821 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4824 unsigned Line
= getLineNumber(BD
->getLocation());
4825 unsigned Column
= getColumnNumber(BD
->getLocation());
4826 StringRef Name
= BD
->getName();
4827 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4828 llvm::DIFile
*Unit
= getOrCreateFile(BD
->getLocation());
4829 // Create the descriptor for the variable.
4830 llvm::DILocalVariable
*D
= DBuilder
.createAutoVariable(
4831 Scope
, Name
, Unit
, Line
, Ty
, CGM
.getLangOpts().Optimize
,
4832 llvm::DINode::FlagZero
, Align
);
4834 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BD
->getBinding())) {
4835 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl())) {
4836 const unsigned fieldIndex
= FD
->getFieldIndex();
4837 const clang::CXXRecordDecl
*parent
=
4838 (const CXXRecordDecl
*)FD
->getParent();
4839 const ASTRecordLayout
&layout
=
4840 CGM
.getContext().getASTRecordLayout(parent
);
4841 const uint64_t fieldOffset
= layout
.getFieldOffset(fieldIndex
);
4843 if (fieldOffset
!= 0) {
4844 // Currently if the field offset is not a multiple of byte, the produced
4845 // location would not be accurate. Therefore give up.
4846 if (fieldOffset
% CGM
.getContext().getCharWidth() != 0)
4849 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4851 CGM
.getContext().toCharUnitsFromBits(fieldOffset
).getQuantity());
4854 } else if (const ArraySubscriptExpr
*ASE
=
4855 dyn_cast
<ArraySubscriptExpr
>(BD
->getBinding())) {
4856 if (const IntegerLiteral
*IL
= dyn_cast
<IntegerLiteral
>(ASE
->getIdx())) {
4857 const uint64_t value
= IL
->getValue().getZExtValue();
4858 const uint64_t typeSize
= CGM
.getContext().getTypeSize(BD
->getType());
4861 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4862 Expr
.push_back(CGM
.getContext()
4863 .toCharUnitsFromBits(value
* typeSize
)
4869 // Insert an llvm.dbg.declare into the current block.
4870 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4871 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4872 Column
, Scope
, CurInlinedAt
),
4873 Builder
.GetInsertBlock());
4878 llvm::DILocalVariable
*
4879 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl
*VD
, llvm::Value
*Storage
,
4880 CGBuilderTy
&Builder
,
4881 const bool UsePointerValue
) {
4882 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4884 if (auto *DD
= dyn_cast
<DecompositionDecl
>(VD
)) {
4885 for (auto *B
: DD
->bindings()) {
4886 EmitDeclare(B
, Storage
, std::nullopt
, Builder
,
4887 VD
->getType()->isReferenceType());
4889 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
4890 // correspond to a user variable.
4894 return EmitDeclare(VD
, Storage
, std::nullopt
, Builder
, UsePointerValue
);
4897 void CGDebugInfo::EmitLabel(const LabelDecl
*D
, CGBuilderTy
&Builder
) {
4898 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4899 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4901 if (D
->hasAttr
<NoDebugAttr
>())
4904 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4905 llvm::DIFile
*Unit
= getOrCreateFile(D
->getLocation());
4907 // Get location information.
4908 unsigned Line
= getLineNumber(D
->getLocation());
4909 unsigned Column
= getColumnNumber(D
->getLocation());
4911 StringRef Name
= D
->getName();
4913 // Create the descriptor for the label.
4915 DBuilder
.createLabel(Scope
, Name
, Unit
, Line
, CGM
.getLangOpts().Optimize
);
4917 // Insert an llvm.dbg.label into the current block.
4918 DBuilder
.insertLabel(L
,
4919 llvm::DILocation::get(CGM
.getLLVMContext(), Line
, Column
,
4920 Scope
, CurInlinedAt
),
4921 Builder
.GetInsertBlock());
4924 llvm::DIType
*CGDebugInfo::CreateSelfType(const QualType
&QualTy
,
4926 llvm::DIType
*CachedTy
= getTypeOrNull(QualTy
);
4929 return DBuilder
.createObjectPointerType(Ty
);
4932 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4933 const VarDecl
*VD
, llvm::Value
*Storage
, CGBuilderTy
&Builder
,
4934 const CGBlockInfo
&blockInfo
, llvm::Instruction
*InsertPoint
) {
4935 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4936 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4938 if (Builder
.GetInsertBlock() == nullptr)
4940 if (VD
->hasAttr
<NoDebugAttr
>())
4943 bool isByRef
= VD
->hasAttr
<BlocksAttr
>();
4945 uint64_t XOffset
= 0;
4946 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
4949 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
).WrappedType
;
4951 Ty
= getOrCreateType(VD
->getType(), Unit
);
4953 // Self is passed along as an implicit non-arg variable in a
4954 // block. Mark it as the object pointer.
4955 if (const auto *IPD
= dyn_cast
<ImplicitParamDecl
>(VD
))
4956 if (IPD
->getParameterKind() == ImplicitParamDecl::ObjCSelf
)
4957 Ty
= CreateSelfType(VD
->getType(), Ty
);
4959 // Get location information.
4960 const unsigned Line
=
4961 getLineNumber(VD
->getLocation().isValid() ? VD
->getLocation() : CurLoc
);
4962 unsigned Column
= getColumnNumber(VD
->getLocation());
4964 const llvm::DataLayout
&target
= CGM
.getDataLayout();
4966 CharUnits offset
= CharUnits::fromQuantity(
4967 target
.getStructLayout(blockInfo
.StructureType
)
4968 ->getElementOffset(blockInfo
.getCapture(VD
).getIndex()));
4970 SmallVector
<uint64_t, 9> addr
;
4971 addr
.push_back(llvm::dwarf::DW_OP_deref
);
4972 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4973 addr
.push_back(offset
.getQuantity());
4975 addr
.push_back(llvm::dwarf::DW_OP_deref
);
4976 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4977 // offset of __forwarding field
4979 CGM
.getContext().toCharUnitsFromBits(target
.getPointerSizeInBits(0));
4980 addr
.push_back(offset
.getQuantity());
4981 addr
.push_back(llvm::dwarf::DW_OP_deref
);
4982 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4983 // offset of x field
4984 offset
= CGM
.getContext().toCharUnitsFromBits(XOffset
);
4985 addr
.push_back(offset
.getQuantity());
4988 // Create the descriptor for the variable.
4989 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
4990 auto *D
= DBuilder
.createAutoVariable(
4991 cast
<llvm::DILocalScope
>(LexicalBlockStack
.back()), VD
->getName(), Unit
,
4992 Line
, Ty
, false, llvm::DINode::FlagZero
, Align
);
4994 // Insert an llvm.dbg.declare into the current block.
4995 auto DL
= llvm::DILocation::get(CGM
.getLLVMContext(), Line
, Column
,
4996 LexicalBlockStack
.back(), CurInlinedAt
);
4997 auto *Expr
= DBuilder
.createExpression(addr
);
4999 DBuilder
.insertDeclare(Storage
, D
, Expr
, DL
, InsertPoint
);
5001 DBuilder
.insertDeclare(Storage
, D
, Expr
, DL
, Builder
.GetInsertBlock());
5004 llvm::DILocalVariable
*
5005 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl
*VD
, llvm::Value
*AI
,
5006 unsigned ArgNo
, CGBuilderTy
&Builder
,
5007 bool UsePointerValue
) {
5008 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5009 return EmitDeclare(VD
, AI
, ArgNo
, Builder
, UsePointerValue
);
5013 struct BlockLayoutChunk
{
5014 uint64_t OffsetInBits
;
5015 const BlockDecl::Capture
*Capture
;
5017 bool operator<(const BlockLayoutChunk
&l
, const BlockLayoutChunk
&r
) {
5018 return l
.OffsetInBits
< r
.OffsetInBits
;
5022 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5023 const CGBlockInfo
&Block
, const ASTContext
&Context
, SourceLocation Loc
,
5024 const llvm::StructLayout
&BlockLayout
, llvm::DIFile
*Unit
,
5025 SmallVectorImpl
<llvm::Metadata
*> &Fields
) {
5026 // Blocks in OpenCL have unique constraints which make the standard fields
5027 // redundant while requiring size and align fields for enqueue_kernel. See
5028 // initializeForBlockHeader in CGBlocks.cpp
5029 if (CGM
.getLangOpts().OpenCL
) {
5030 Fields
.push_back(createFieldType("__size", Context
.IntTy
, Loc
, AS_public
,
5031 BlockLayout
.getElementOffsetInBits(0),
5033 Fields
.push_back(createFieldType("__align", Context
.IntTy
, Loc
, AS_public
,
5034 BlockLayout
.getElementOffsetInBits(1),
5037 Fields
.push_back(createFieldType("__isa", Context
.VoidPtrTy
, Loc
, AS_public
,
5038 BlockLayout
.getElementOffsetInBits(0),
5040 Fields
.push_back(createFieldType("__flags", Context
.IntTy
, Loc
, AS_public
,
5041 BlockLayout
.getElementOffsetInBits(1),
5044 createFieldType("__reserved", Context
.IntTy
, Loc
, AS_public
,
5045 BlockLayout
.getElementOffsetInBits(2), Unit
, Unit
));
5046 auto *FnTy
= Block
.getBlockExpr()->getFunctionType();
5047 auto FnPtrType
= CGM
.getContext().getPointerType(FnTy
->desugar());
5048 Fields
.push_back(createFieldType("__FuncPtr", FnPtrType
, Loc
, AS_public
,
5049 BlockLayout
.getElementOffsetInBits(3),
5051 Fields
.push_back(createFieldType(
5053 Context
.getPointerType(Block
.NeedsCopyDispose
5054 ? Context
.getBlockDescriptorExtendedType()
5055 : Context
.getBlockDescriptorType()),
5056 Loc
, AS_public
, BlockLayout
.getElementOffsetInBits(4), Unit
, Unit
));
5060 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo
&block
,
5063 llvm::AllocaInst
*Alloca
,
5064 CGBuilderTy
&Builder
) {
5065 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5066 ASTContext
&C
= CGM
.getContext();
5067 const BlockDecl
*blockDecl
= block
.getBlockDecl();
5069 // Collect some general information about the block's location.
5070 SourceLocation loc
= blockDecl
->getCaretLocation();
5071 llvm::DIFile
*tunit
= getOrCreateFile(loc
);
5072 unsigned line
= getLineNumber(loc
);
5073 unsigned column
= getColumnNumber(loc
);
5075 // Build the debug-info type for the block literal.
5076 getDeclContextDescriptor(blockDecl
);
5078 const llvm::StructLayout
*blockLayout
=
5079 CGM
.getDataLayout().getStructLayout(block
.StructureType
);
5081 SmallVector
<llvm::Metadata
*, 16> fields
;
5082 collectDefaultFieldsForBlockLiteralDeclare(block
, C
, loc
, *blockLayout
, tunit
,
5085 // We want to sort the captures by offset, not because DWARF
5086 // requires this, but because we're paranoid about debuggers.
5087 SmallVector
<BlockLayoutChunk
, 8> chunks
;
5090 if (blockDecl
->capturesCXXThis()) {
5091 BlockLayoutChunk chunk
;
5092 chunk
.OffsetInBits
=
5093 blockLayout
->getElementOffsetInBits(block
.CXXThisIndex
);
5094 chunk
.Capture
= nullptr;
5095 chunks
.push_back(chunk
);
5098 // Variable captures.
5099 for (const auto &capture
: blockDecl
->captures()) {
5100 const VarDecl
*variable
= capture
.getVariable();
5101 const CGBlockInfo::Capture
&captureInfo
= block
.getCapture(variable
);
5103 // Ignore constant captures.
5104 if (captureInfo
.isConstant())
5107 BlockLayoutChunk chunk
;
5108 chunk
.OffsetInBits
=
5109 blockLayout
->getElementOffsetInBits(captureInfo
.getIndex());
5110 chunk
.Capture
= &capture
;
5111 chunks
.push_back(chunk
);
5115 llvm::array_pod_sort(chunks
.begin(), chunks
.end());
5117 for (const BlockLayoutChunk
&Chunk
: chunks
) {
5118 uint64_t offsetInBits
= Chunk
.OffsetInBits
;
5119 const BlockDecl::Capture
*capture
= Chunk
.Capture
;
5121 // If we have a null capture, this must be the C++ 'this' capture.
5125 cast_or_null
<CXXMethodDecl
>(blockDecl
->getNonClosureContext()))
5126 type
= Method
->getThisType();
5127 else if (auto *RDecl
= dyn_cast
<CXXRecordDecl
>(blockDecl
->getParent()))
5128 type
= QualType(RDecl
->getTypeForDecl(), 0);
5130 llvm_unreachable("unexpected block declcontext");
5132 fields
.push_back(createFieldType("this", type
, loc
, AS_public
,
5133 offsetInBits
, tunit
, tunit
));
5137 const VarDecl
*variable
= capture
->getVariable();
5138 StringRef name
= variable
->getName();
5140 llvm::DIType
*fieldType
;
5141 if (capture
->isByRef()) {
5142 TypeInfo PtrInfo
= C
.getTypeInfo(C
.VoidPtrTy
);
5143 auto Align
= PtrInfo
.isAlignRequired() ? PtrInfo
.Align
: 0;
5144 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5147 EmitTypeForVarWithBlocksAttr(variable
, &xoffset
).BlockByRefWrapper
;
5148 fieldType
= DBuilder
.createPointerType(fieldType
, PtrInfo
.Width
);
5149 fieldType
= DBuilder
.createMemberType(tunit
, name
, tunit
, line
,
5150 PtrInfo
.Width
, Align
, offsetInBits
,
5151 llvm::DINode::FlagZero
, fieldType
);
5153 auto Align
= getDeclAlignIfRequired(variable
, CGM
.getContext());
5154 fieldType
= createFieldType(name
, variable
->getType(), loc
, AS_public
,
5155 offsetInBits
, Align
, tunit
, tunit
);
5157 fields
.push_back(fieldType
);
5160 SmallString
<36> typeName
;
5161 llvm::raw_svector_ostream(typeName
)
5162 << "__block_literal_" << CGM
.getUniqueBlockCount();
5164 llvm::DINodeArray fieldsArray
= DBuilder
.getOrCreateArray(fields
);
5166 llvm::DIType
*type
=
5167 DBuilder
.createStructType(tunit
, typeName
.str(), tunit
, line
,
5168 CGM
.getContext().toBits(block
.BlockSize
), 0,
5169 llvm::DINode::FlagZero
, nullptr, fieldsArray
);
5170 type
= DBuilder
.createPointerType(type
, CGM
.PointerWidthInBits
);
5172 // Get overall information about the block.
5173 llvm::DINode::DIFlags flags
= llvm::DINode::FlagArtificial
;
5174 auto *scope
= cast
<llvm::DILocalScope
>(LexicalBlockStack
.back());
5176 // Create the descriptor for the parameter.
5177 auto *debugVar
= DBuilder
.createParameterVariable(
5178 scope
, Name
, ArgNo
, tunit
, line
, type
, CGM
.getLangOpts().Optimize
, flags
);
5180 // Insert an llvm.dbg.declare into the current block.
5181 DBuilder
.insertDeclare(Alloca
, debugVar
, DBuilder
.createExpression(),
5182 llvm::DILocation::get(CGM
.getLLVMContext(), line
,
5183 column
, scope
, CurInlinedAt
),
5184 Builder
.GetInsertBlock());
5187 llvm::DIDerivedType
*
5188 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl
*D
) {
5189 if (!D
|| !D
->isStaticDataMember())
5192 auto MI
= StaticDataMemberCache
.find(D
->getCanonicalDecl());
5193 if (MI
!= StaticDataMemberCache
.end()) {
5194 assert(MI
->second
&& "Static data member declaration should still exist");
5198 // If the member wasn't found in the cache, lazily construct and add it to the
5199 // type (used when a limited form of the type is emitted).
5200 auto DC
= D
->getDeclContext();
5201 auto *Ctxt
= cast
<llvm::DICompositeType
>(getDeclContextDescriptor(D
));
5202 return CreateRecordStaticField(D
, Ctxt
, cast
<RecordDecl
>(DC
));
5205 llvm::DIGlobalVariableExpression
*CGDebugInfo::CollectAnonRecordDecls(
5206 const RecordDecl
*RD
, llvm::DIFile
*Unit
, unsigned LineNo
,
5207 StringRef LinkageName
, llvm::GlobalVariable
*Var
, llvm::DIScope
*DContext
) {
5208 llvm::DIGlobalVariableExpression
*GVE
= nullptr;
5210 for (const auto *Field
: RD
->fields()) {
5211 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
5212 StringRef FieldName
= Field
->getName();
5214 // Ignore unnamed fields, but recurse into anonymous records.
5215 if (FieldName
.empty()) {
5216 if (const auto *RT
= dyn_cast
<RecordType
>(Field
->getType()))
5217 GVE
= CollectAnonRecordDecls(RT
->getDecl(), Unit
, LineNo
, LinkageName
,
5221 // Use VarDecl's Tag, Scope and Line number.
5222 GVE
= DBuilder
.createGlobalVariableExpression(
5223 DContext
, FieldName
, LinkageName
, Unit
, LineNo
, FieldTy
,
5224 Var
->hasLocalLinkage());
5225 Var
->addDebugInfo(GVE
);
5230 static bool ReferencesAnonymousEntity(ArrayRef
<TemplateArgument
> Args
);
5231 static bool ReferencesAnonymousEntity(RecordType
*RT
) {
5232 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5233 // info we produce in the DWARF, so we can't get Clang's full name back.
5234 // But so long as it's not one of those, it doesn't matter if some sub-type
5235 // of the record (a template parameter) can't be reconstituted - because the
5236 // un-reconstitutable type itself will carry its own name.
5237 const auto *RD
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
5240 if (!RD
->getIdentifier())
5242 auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
);
5245 return ReferencesAnonymousEntity(TSpecial
->getTemplateArgs().asArray());
5247 static bool ReferencesAnonymousEntity(ArrayRef
<TemplateArgument
> Args
) {
5248 return llvm::any_of(Args
, [&](const TemplateArgument
&TA
) {
5249 switch (TA
.getKind()) {
5250 case TemplateArgument::Pack
:
5251 return ReferencesAnonymousEntity(TA
.getPackAsArray());
5252 case TemplateArgument::Type
: {
5253 struct ReferencesAnonymous
5254 : public RecursiveASTVisitor
<ReferencesAnonymous
> {
5255 bool RefAnon
= false;
5256 bool VisitRecordType(RecordType
*RT
) {
5257 if (ReferencesAnonymousEntity(RT
)) {
5264 ReferencesAnonymous RT
;
5265 RT
.TraverseType(TA
.getAsType());
5277 struct ReconstitutableType
: public RecursiveASTVisitor
<ReconstitutableType
> {
5278 bool Reconstitutable
= true;
5279 bool VisitVectorType(VectorType
*FT
) {
5280 Reconstitutable
= false;
5283 bool VisitAtomicType(AtomicType
*FT
) {
5284 Reconstitutable
= false;
5287 bool VisitType(Type
*T
) {
5288 // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5289 // the DWARF, only the byte width.
5290 if (T
->isBitIntType()) {
5291 Reconstitutable
= false;
5296 bool TraverseEnumType(EnumType
*ET
) {
5297 // Unnamed enums can't be reconstituted due to a lack of column info we
5298 // produce in the DWARF, so we can't get Clang's full name back.
5299 if (const auto *ED
= dyn_cast
<EnumDecl
>(ET
->getDecl())) {
5300 if (!ED
->getIdentifier()) {
5301 Reconstitutable
= false;
5304 if (!ED
->isExternallyVisible()) {
5305 Reconstitutable
= false;
5311 bool VisitFunctionProtoType(FunctionProtoType
*FT
) {
5312 // noexcept is not encoded in DWARF, so the reversi
5313 Reconstitutable
&= !isNoexceptExceptionSpec(FT
->getExceptionSpecType());
5314 Reconstitutable
&= !FT
->getNoReturnAttr();
5315 return Reconstitutable
;
5317 bool VisitRecordType(RecordType
*RT
) {
5318 if (ReferencesAnonymousEntity(RT
)) {
5319 Reconstitutable
= false;
5325 } // anonymous namespace
5327 // Test whether a type name could be rebuilt from emitted debug info.
5328 static bool IsReconstitutableType(QualType QT
) {
5329 ReconstitutableType T
;
5331 return T
.Reconstitutable
;
5334 std::string
CGDebugInfo::GetName(const Decl
*D
, bool Qualified
) const {
5336 llvm::raw_string_ostream
OS(Name
);
5337 const NamedDecl
*ND
= dyn_cast
<NamedDecl
>(D
);
5340 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind
=
5341 CGM
.getCodeGenOpts().getDebugSimpleTemplateNames();
5343 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5344 TemplateNamesKind
= llvm::codegenoptions::DebugTemplateNamesKind::Full
;
5346 std::optional
<TemplateArgs
> Args
;
5348 bool IsOperatorOverload
= false; // isa<CXXConversionDecl>(ND);
5349 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
)) {
5350 Args
= GetTemplateArgs(RD
);
5351 } else if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
)) {
5352 Args
= GetTemplateArgs(FD
);
5353 auto NameKind
= ND
->getDeclName().getNameKind();
5354 IsOperatorOverload
|=
5355 NameKind
== DeclarationName::CXXOperatorName
||
5356 NameKind
== DeclarationName::CXXConversionFunctionName
;
5357 } else if (auto *VD
= dyn_cast
<VarDecl
>(ND
)) {
5358 Args
= GetTemplateArgs(VD
);
5360 std::function
<bool(ArrayRef
<TemplateArgument
>)> HasReconstitutableArgs
=
5361 [&](ArrayRef
<TemplateArgument
> Args
) {
5362 return llvm::all_of(Args
, [&](const TemplateArgument
&TA
) {
5363 switch (TA
.getKind()) {
5364 case TemplateArgument::Template
:
5365 // Easy to reconstitute - the value of the parameter in the debug
5366 // info is the string name of the template. (so the template name
5367 // itself won't benefit from any name rebuilding, but that's a
5368 // representational limitation - maybe DWARF could be
5369 // changed/improved to use some more structural representation)
5371 case TemplateArgument::Declaration
:
5372 // Reference and pointer non-type template parameters point to
5373 // variables, functions, etc and their value is, at best (for
5374 // variables) represented as an address - not a reference to the
5375 // DWARF describing the variable/function/etc. This makes it hard,
5376 // possibly impossible to rebuild the original name - looking up the
5377 // address in the executable file's symbol table would be needed.
5379 case TemplateArgument::NullPtr
:
5380 // These could be rebuilt, but figured they're close enough to the
5381 // declaration case, and not worth rebuilding.
5383 case TemplateArgument::Pack
:
5384 // A pack is invalid if any of the elements of the pack are invalid.
5385 return HasReconstitutableArgs(TA
.getPackAsArray());
5386 case TemplateArgument::Integral
:
5387 // Larger integers get encoded as DWARF blocks which are a bit
5388 // harder to parse back into a large integer, etc - so punting on
5389 // this for now. Re-parsing the integers back into APInt is probably
5390 // feasible some day.
5391 return TA
.getAsIntegral().getBitWidth() <= 64 &&
5392 IsReconstitutableType(TA
.getIntegralType());
5393 case TemplateArgument::Type
:
5394 return IsReconstitutableType(TA
.getAsType());
5396 llvm_unreachable("Other, unresolved, template arguments should "
5397 "not be seen here");
5401 // A conversion operator presents complications/ambiguity if there's a
5402 // conversion to class template that is itself a template, eg:
5403 // template<typename T>
5404 // operator ns::t1<T, int>();
5405 // This should be named, eg: "operator ns::t1<float, int><float>"
5406 // (ignoring clang bug that means this is currently "operator t1<float>")
5407 // but if the arguments were stripped, the consumer couldn't differentiate
5408 // whether the template argument list for the conversion type was the
5409 // function's argument list (& no reconstitution was needed) or not.
5410 // This could be handled if reconstitutable names had a separate attribute
5411 // annotating them as such - this would remove the ambiguity.
5413 // Alternatively the template argument list could be parsed enough to check
5414 // whether there's one list or two, then compare that with the DWARF
5415 // description of the return type and the template argument lists to determine
5416 // how many lists there should be and if one is missing it could be assumed(?)
5417 // to be the function's template argument list & then be rebuilt.
5419 // Other operator overloads that aren't conversion operators could be
5420 // reconstituted but would require a bit more nuance about detecting the
5421 // difference between these different operators during that rebuilding.
5422 bool Reconstitutable
=
5423 Args
&& HasReconstitutableArgs(Args
->Args
) && !IsOperatorOverload
;
5425 PrintingPolicy PP
= getPrintingPolicy();
5427 if (TemplateNamesKind
== llvm::codegenoptions::DebugTemplateNamesKind::Full
||
5429 ND
->getNameForDiagnostic(OS
, PP
, Qualified
);
5431 bool Mangled
= TemplateNamesKind
==
5432 llvm::codegenoptions::DebugTemplateNamesKind::Mangled
;
5433 // check if it's a template
5437 OS
<< ND
->getDeclName();
5438 std::string EncodedOriginalName
;
5439 llvm::raw_string_ostream
EncodedOriginalNameOS(EncodedOriginalName
);
5440 EncodedOriginalNameOS
<< ND
->getDeclName();
5444 printTemplateArgumentList(OS
, Args
->Args
, PP
);
5445 printTemplateArgumentList(EncodedOriginalNameOS
, Args
->Args
, PP
);
5447 std::string CanonicalOriginalName
;
5448 llvm::raw_string_ostream
OriginalOS(CanonicalOriginalName
);
5449 ND
->getNameForDiagnostic(OriginalOS
, PP
, Qualified
);
5450 assert(EncodedOriginalNameOS
.str() == OriginalOS
.str());
5457 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable
*Var
,
5459 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5460 if (D
->hasAttr
<NoDebugAttr
>())
5463 llvm::TimeTraceScope
TimeScope("DebugGlobalVariable", [&]() {
5464 return GetName(D
, true);
5467 // If we already created a DIGlobalVariable for this declaration, just attach
5468 // it to the llvm::GlobalVariable.
5469 auto Cached
= DeclCache
.find(D
->getCanonicalDecl());
5470 if (Cached
!= DeclCache
.end())
5471 return Var
->addDebugInfo(
5472 cast
<llvm::DIGlobalVariableExpression
>(Cached
->second
));
5474 // Create global variable debug descriptor.
5475 llvm::DIFile
*Unit
= nullptr;
5476 llvm::DIScope
*DContext
= nullptr;
5478 StringRef DeclName
, LinkageName
;
5480 llvm::MDTuple
*TemplateParameters
= nullptr;
5481 collectVarDeclProps(D
, Unit
, LineNo
, T
, DeclName
, LinkageName
,
5482 TemplateParameters
, DContext
);
5484 // Attempt to store one global variable for the declaration - even if we
5485 // emit a lot of fields.
5486 llvm::DIGlobalVariableExpression
*GVE
= nullptr;
5488 // If this is an anonymous union then we'll want to emit a global
5489 // variable for each member of the anonymous union so that it's possible
5490 // to find the name of any field in the union.
5491 if (T
->isUnionType() && DeclName
.empty()) {
5492 const RecordDecl
*RD
= T
->castAs
<RecordType
>()->getDecl();
5493 assert(RD
->isAnonymousStructOrUnion() &&
5494 "unnamed non-anonymous struct or union?");
5495 GVE
= CollectAnonRecordDecls(RD
, Unit
, LineNo
, LinkageName
, Var
, DContext
);
5497 auto Align
= getDeclAlignIfRequired(D
, CGM
.getContext());
5499 SmallVector
<uint64_t, 4> Expr
;
5500 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(D
->getType());
5501 if (CGM
.getLangOpts().CUDA
&& CGM
.getLangOpts().CUDAIsDevice
) {
5502 if (D
->hasAttr
<CUDASharedAttr
>())
5504 CGM
.getContext().getTargetAddressSpace(LangAS::cuda_shared
);
5505 else if (D
->hasAttr
<CUDAConstantAttr
>())
5507 CGM
.getContext().getTargetAddressSpace(LangAS::cuda_constant
);
5509 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
5511 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
5512 GVE
= DBuilder
.createGlobalVariableExpression(
5513 DContext
, DeclName
, LinkageName
, Unit
, LineNo
, getOrCreateType(T
, Unit
),
5514 Var
->hasLocalLinkage(), true,
5515 Expr
.empty() ? nullptr : DBuilder
.createExpression(Expr
),
5516 getOrCreateStaticDataMemberDeclarationOrNull(D
), TemplateParameters
,
5517 Align
, Annotations
);
5518 Var
->addDebugInfo(GVE
);
5520 DeclCache
[D
->getCanonicalDecl()].reset(GVE
);
5523 void CGDebugInfo::EmitGlobalVariable(const ValueDecl
*VD
, const APValue
&Init
) {
5524 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5525 if (VD
->hasAttr
<NoDebugAttr
>())
5527 llvm::TimeTraceScope
TimeScope("DebugConstGlobalVariable", [&]() {
5528 return GetName(VD
, true);
5531 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
5532 // Create the descriptor for the variable.
5533 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
5534 StringRef Name
= VD
->getName();
5535 llvm::DIType
*Ty
= getOrCreateType(VD
->getType(), Unit
);
5537 if (const auto *ECD
= dyn_cast
<EnumConstantDecl
>(VD
)) {
5538 const auto *ED
= cast
<EnumDecl
>(ECD
->getDeclContext());
5539 assert(isa
<EnumType
>(ED
->getTypeForDecl()) && "Enum without EnumType?");
5541 if (CGM
.getCodeGenOpts().EmitCodeView
) {
5542 // If CodeView, emit enums as global variables, unless they are defined
5543 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5544 // enums in classes, and because it is difficult to attach this scope
5545 // information to the global variable.
5546 if (isa
<RecordDecl
>(ED
->getDeclContext()))
5549 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5550 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5551 // first time `ZERO` is referenced in a function.
5552 llvm::DIType
*EDTy
=
5553 getOrCreateType(QualType(ED
->getTypeForDecl(), 0), Unit
);
5554 assert (EDTy
->getTag() == llvm::dwarf::DW_TAG_enumeration_type
);
5560 // Do not emit separate definitions for function local consts.
5561 if (isa
<FunctionDecl
>(VD
->getDeclContext()))
5564 VD
= cast
<ValueDecl
>(VD
->getCanonicalDecl());
5565 auto *VarD
= dyn_cast
<VarDecl
>(VD
);
5566 if (VarD
&& VarD
->isStaticDataMember()) {
5567 auto *RD
= cast
<RecordDecl
>(VarD
->getDeclContext());
5568 getDeclContextDescriptor(VarD
);
5569 // Ensure that the type is retained even though it's otherwise unreferenced.
5571 // FIXME: This is probably unnecessary, since Ty should reference RD
5572 // through its scope.
5573 RetainedTypes
.push_back(
5574 CGM
.getContext().getRecordType(RD
).getAsOpaquePtr());
5578 llvm::DIScope
*DContext
= getDeclContextDescriptor(VD
);
5580 auto &GV
= DeclCache
[VD
];
5583 llvm::DIExpression
*InitExpr
= nullptr;
5584 if (CGM
.getContext().getTypeSize(VD
->getType()) <= 64) {
5585 // FIXME: Add a representation for integer constants wider than 64 bits.
5587 const llvm::APSInt
&InitInt
= Init
.getInt();
5588 std::optional
<uint64_t> InitIntOpt
;
5589 if (InitInt
.isUnsigned())
5590 InitIntOpt
= InitInt
.tryZExtValue();
5591 else if (auto tmp
= InitInt
.trySExtValue(); tmp
.has_value())
5592 // Transform a signed optional to unsigned optional. When cpp 23 comes,
5593 // use std::optional::transform
5594 InitIntOpt
= (uint64_t)tmp
.value();
5596 InitExpr
= DBuilder
.createConstantValueExpression(InitIntOpt
.value());
5597 } else if (Init
.isFloat())
5598 InitExpr
= DBuilder
.createConstantValueExpression(
5599 Init
.getFloat().bitcastToAPInt().getZExtValue());
5602 llvm::MDTuple
*TemplateParameters
= nullptr;
5604 if (isa
<VarTemplateSpecializationDecl
>(VD
))
5606 llvm::DINodeArray parameterNodes
= CollectVarTemplateParams(VarD
, &*Unit
);
5607 TemplateParameters
= parameterNodes
.get();
5610 GV
.reset(DBuilder
.createGlobalVariableExpression(
5611 DContext
, Name
, StringRef(), Unit
, getLineNumber(VD
->getLocation()), Ty
,
5612 true, true, InitExpr
, getOrCreateStaticDataMemberDeclarationOrNull(VarD
),
5613 TemplateParameters
, Align
));
5616 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable
*Var
,
5618 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5619 if (D
->hasAttr
<NoDebugAttr
>())
5622 auto Align
= getDeclAlignIfRequired(D
, CGM
.getContext());
5623 llvm::DIFile
*Unit
= getOrCreateFile(D
->getLocation());
5624 StringRef Name
= D
->getName();
5625 llvm::DIType
*Ty
= getOrCreateType(D
->getType(), Unit
);
5627 llvm::DIScope
*DContext
= getDeclContextDescriptor(D
);
5628 llvm::DIGlobalVariableExpression
*GVE
=
5629 DBuilder
.createGlobalVariableExpression(
5630 DContext
, Name
, StringRef(), Unit
, getLineNumber(D
->getLocation()),
5631 Ty
, false, false, nullptr, nullptr, nullptr, Align
);
5632 Var
->addDebugInfo(GVE
);
5635 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue
*GV
,
5636 const GlobalDecl GD
) {
5640 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5643 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
5644 if (D
->hasAttr
<NoDebugAttr
>())
5647 auto AliaseeDecl
= CGM
.getMangledNameDecl(GV
->getName());
5651 // FIXME: Aliasee not declared yet - possibly declared later
5654 // 1 extern int newname __attribute__((alias("oldname")));
5655 // 2 int oldname = 1;
5657 // No debug info would be generated for 'newname' in this case.
5659 // Fix compiler to generate "newname" as imported_declaration
5660 // pointing to the DIE of "oldname".
5662 if (!(DI
= getDeclarationOrDefinition(
5663 AliaseeDecl
.getCanonicalDecl().getDecl())))
5666 llvm::DIScope
*DContext
= getDeclContextDescriptor(D
);
5667 auto Loc
= D
->getLocation();
5669 llvm::DIImportedEntity
*ImportDI
= DBuilder
.createImportedDeclaration(
5670 DContext
, DI
, getOrCreateFile(Loc
), getLineNumber(Loc
), D
->getName());
5672 // Record this DIE in the cache for nested declaration reference.
5673 ImportedDeclCache
[GD
.getCanonicalDecl().getDecl()].reset(ImportDI
);
5676 void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable
*GV
,
5677 const StringLiteral
*S
) {
5678 SourceLocation Loc
= S
->getStrTokenLoc(0);
5679 PresumedLoc PLoc
= CGM
.getContext().getSourceManager().getPresumedLoc(Loc
);
5680 if (!PLoc
.isValid())
5683 llvm::DIFile
*File
= getOrCreateFile(Loc
);
5684 llvm::DIGlobalVariableExpression
*Debug
=
5685 DBuilder
.createGlobalVariableExpression(
5686 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc
),
5687 getLineNumber(Loc
), getOrCreateType(S
->getType(), File
), true);
5688 GV
->addDebugInfo(Debug
);
5691 llvm::DIScope
*CGDebugInfo::getCurrentContextDescriptor(const Decl
*D
) {
5692 if (!LexicalBlockStack
.empty())
5693 return LexicalBlockStack
.back();
5694 llvm::DIScope
*Mod
= getParentModuleOrNull(D
);
5695 return getContextDescriptor(D
, Mod
? Mod
: TheCU
);
5698 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl
&UD
) {
5699 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5701 const NamespaceDecl
*NSDecl
= UD
.getNominatedNamespace();
5702 if (!NSDecl
->isAnonymousNamespace() ||
5703 CGM
.getCodeGenOpts().DebugExplicitImport
) {
5704 auto Loc
= UD
.getLocation();
5707 DBuilder
.createImportedModule(
5708 getCurrentContextDescriptor(cast
<Decl
>(UD
.getDeclContext())),
5709 getOrCreateNamespace(NSDecl
), getOrCreateFile(Loc
), getLineNumber(Loc
));
5713 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl
&USD
) {
5714 if (llvm::DINode
*Target
=
5715 getDeclarationOrDefinition(USD
.getUnderlyingDecl())) {
5716 auto Loc
= USD
.getLocation();
5717 DBuilder
.createImportedDeclaration(
5718 getCurrentContextDescriptor(cast
<Decl
>(USD
.getDeclContext())), Target
,
5719 getOrCreateFile(Loc
), getLineNumber(Loc
));
5723 void CGDebugInfo::EmitUsingDecl(const UsingDecl
&UD
) {
5724 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5726 assert(UD
.shadow_size() &&
5727 "We shouldn't be codegening an invalid UsingDecl containing no decls");
5729 for (const auto *USD
: UD
.shadows()) {
5730 // FIXME: Skip functions with undeduced auto return type for now since we
5731 // don't currently have the plumbing for separate declarations & definitions
5732 // of free functions and mismatched types (auto in the declaration, concrete
5733 // return type in the definition)
5734 if (const auto *FD
= dyn_cast
<FunctionDecl
>(USD
->getUnderlyingDecl()))
5735 if (const auto *AT
= FD
->getType()
5736 ->castAs
<FunctionProtoType
>()
5737 ->getContainedAutoType())
5738 if (AT
->getDeducedType().isNull())
5741 EmitUsingShadowDecl(*USD
);
5742 // Emitting one decl is sufficient - debuggers can detect that this is an
5743 // overloaded name & provide lookup for all the overloads.
5748 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl
&UD
) {
5749 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5751 assert(UD
.shadow_size() &&
5752 "We shouldn't be codegening an invalid UsingEnumDecl"
5753 " containing no decls");
5755 for (const auto *USD
: UD
.shadows())
5756 EmitUsingShadowDecl(*USD
);
5759 void CGDebugInfo::EmitImportDecl(const ImportDecl
&ID
) {
5760 if (CGM
.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB
)
5762 if (Module
*M
= ID
.getImportedModule()) {
5763 auto Info
= ASTSourceDescriptor(*M
);
5764 auto Loc
= ID
.getLocation();
5765 DBuilder
.createImportedDeclaration(
5766 getCurrentContextDescriptor(cast
<Decl
>(ID
.getDeclContext())),
5767 getOrCreateModuleRef(Info
, DebugTypeExtRefs
), getOrCreateFile(Loc
),
5768 getLineNumber(Loc
));
5772 llvm::DIImportedEntity
*
5773 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl
&NA
) {
5774 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5776 auto &VH
= NamespaceAliasCache
[&NA
];
5778 return cast
<llvm::DIImportedEntity
>(VH
);
5779 llvm::DIImportedEntity
*R
;
5780 auto Loc
= NA
.getLocation();
5781 if (const auto *Underlying
=
5782 dyn_cast
<NamespaceAliasDecl
>(NA
.getAliasedNamespace()))
5783 // This could cache & dedup here rather than relying on metadata deduping.
5784 R
= DBuilder
.createImportedDeclaration(
5785 getCurrentContextDescriptor(cast
<Decl
>(NA
.getDeclContext())),
5786 EmitNamespaceAlias(*Underlying
), getOrCreateFile(Loc
),
5787 getLineNumber(Loc
), NA
.getName());
5789 R
= DBuilder
.createImportedDeclaration(
5790 getCurrentContextDescriptor(cast
<Decl
>(NA
.getDeclContext())),
5791 getOrCreateNamespace(cast
<NamespaceDecl
>(NA
.getAliasedNamespace())),
5792 getOrCreateFile(Loc
), getLineNumber(Loc
), NA
.getName());
5798 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl
*NSDecl
) {
5799 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5800 // if necessary, and this way multiple declarations of the same namespace in
5801 // different parent modules stay distinct.
5802 auto I
= NamespaceCache
.find(NSDecl
);
5803 if (I
!= NamespaceCache
.end())
5804 return cast
<llvm::DINamespace
>(I
->second
);
5806 llvm::DIScope
*Context
= getDeclContextDescriptor(NSDecl
);
5807 // Don't trust the context if it is a DIModule (see comment above).
5808 llvm::DINamespace
*NS
=
5809 DBuilder
.createNameSpace(Context
, NSDecl
->getName(), NSDecl
->isInline());
5810 NamespaceCache
[NSDecl
].reset(NS
);
5814 void CGDebugInfo::setDwoId(uint64_t Signature
) {
5815 assert(TheCU
&& "no main compile unit");
5816 TheCU
->setDWOId(Signature
);
5819 void CGDebugInfo::finalize() {
5820 // Creating types might create further types - invalidating the current
5821 // element and the size(), so don't cache/reference them.
5822 for (size_t i
= 0; i
!= ObjCInterfaceCache
.size(); ++i
) {
5823 ObjCInterfaceCacheEntry E
= ObjCInterfaceCache
[i
];
5824 llvm::DIType
*Ty
= E
.Type
->getDecl()->getDefinition()
5825 ? CreateTypeDefinition(E
.Type
, E
.Unit
)
5827 DBuilder
.replaceTemporary(llvm::TempDIType(E
.Decl
), Ty
);
5830 // Add methods to interface.
5831 for (const auto &P
: ObjCMethodCache
) {
5832 if (P
.second
.empty())
5835 QualType
QTy(P
.first
->getTypeForDecl(), 0);
5836 auto It
= TypeCache
.find(QTy
.getAsOpaquePtr());
5837 assert(It
!= TypeCache
.end());
5839 llvm::DICompositeType
*InterfaceDecl
=
5840 cast
<llvm::DICompositeType
>(It
->second
);
5842 auto CurElts
= InterfaceDecl
->getElements();
5843 SmallVector
<llvm::Metadata
*, 16> EltTys(CurElts
.begin(), CurElts
.end());
5845 // For DWARF v4 or earlier, only add objc_direct methods.
5846 for (auto &SubprogramDirect
: P
.second
)
5847 if (CGM
.getCodeGenOpts().DwarfVersion
>= 5 || SubprogramDirect
.getInt())
5848 EltTys
.push_back(SubprogramDirect
.getPointer());
5850 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
5851 DBuilder
.replaceArrays(InterfaceDecl
, Elements
);
5854 for (const auto &P
: ReplaceMap
) {
5856 auto *Ty
= cast
<llvm::DIType
>(P
.second
);
5857 assert(Ty
->isForwardDecl());
5859 auto It
= TypeCache
.find(P
.first
);
5860 assert(It
!= TypeCache
.end());
5863 DBuilder
.replaceTemporary(llvm::TempDIType(Ty
),
5864 cast
<llvm::DIType
>(It
->second
));
5867 for (const auto &P
: FwdDeclReplaceMap
) {
5869 llvm::TempMDNode
FwdDecl(cast
<llvm::MDNode
>(P
.second
));
5870 llvm::Metadata
*Repl
;
5872 auto It
= DeclCache
.find(P
.first
);
5873 // If there has been no definition for the declaration, call RAUW
5874 // with ourselves, that will destroy the temporary MDNode and
5875 // replace it with a standard one, avoiding leaking memory.
5876 if (It
== DeclCache
.end())
5881 if (auto *GVE
= dyn_cast_or_null
<llvm::DIGlobalVariableExpression
>(Repl
))
5882 Repl
= GVE
->getVariable();
5883 DBuilder
.replaceTemporary(std::move(FwdDecl
), cast
<llvm::MDNode
>(Repl
));
5886 // We keep our own list of retained types, because we need to look
5887 // up the final type in the type cache.
5888 for (auto &RT
: RetainedTypes
)
5889 if (auto MD
= TypeCache
[RT
])
5890 DBuilder
.retainType(cast
<llvm::DIType
>(MD
));
5892 DBuilder
.finalize();
5895 // Don't ignore in case of explicit cast where it is referenced indirectly.
5896 void CGDebugInfo::EmitExplicitCastType(QualType Ty
) {
5897 if (CGM
.getCodeGenOpts().hasReducedDebugInfo())
5898 if (auto *DieTy
= getOrCreateType(Ty
, TheCU
->getFile()))
5899 DBuilder
.retainType(DieTy
);
5902 void CGDebugInfo::EmitAndRetainType(QualType Ty
) {
5903 if (CGM
.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5904 if (auto *DieTy
= getOrCreateType(Ty
, TheCU
->getFile()))
5905 DBuilder
.retainType(DieTy
);
5908 llvm::DebugLoc
CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc
) {
5909 if (LexicalBlockStack
.empty())
5910 return llvm::DebugLoc();
5912 llvm::MDNode
*Scope
= LexicalBlockStack
.back();
5913 return llvm::DILocation::get(CGM
.getLLVMContext(), getLineNumber(Loc
),
5914 getColumnNumber(Loc
), Scope
);
5917 llvm::DINode::DIFlags
CGDebugInfo::getCallSiteRelatedAttrs() const {
5918 // Call site-related attributes are only useful in optimized programs, and
5919 // when there's a possibility of debugging backtraces.
5920 if (!CGM
.getLangOpts().Optimize
||
5921 DebugKind
== llvm::codegenoptions::NoDebugInfo
||
5922 DebugKind
== llvm::codegenoptions::LocTrackingOnly
)
5923 return llvm::DINode::FlagZero
;
5925 // Call site-related attributes are available in DWARF v5. Some debuggers,
5926 // while not fully DWARF v5-compliant, may accept these attributes as if they
5927 // were part of DWARF v4.
5928 bool SupportsDWARFv4Ext
=
5929 CGM
.getCodeGenOpts().DwarfVersion
== 4 &&
5930 (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
||
5931 CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB
);
5933 if (!SupportsDWARFv4Ext
&& CGM
.getCodeGenOpts().DwarfVersion
< 5)
5934 return llvm::DINode::FlagZero
;
5936 return llvm::DINode::FlagAllCallsDescribed
;