clang 20.0.0git
CGDebugInfo.cpp
Go to the documentation of this file.
1//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the debug information generation while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGBlocks.h"
15#include "CGCXXABI.h"
16#include "CGObjCRuntime.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "ConstantEmitter.h"
21#include "TargetInfo.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
34#include "clang/Basic/Version.h"
38#include "clang/Lex/ModuleMap.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DerivedTypes.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/Metadata.h"
49#include "llvm/IR/Module.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"
55#include <optional>
56using namespace clang;
57using namespace clang::CodeGen;
58
59static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
60 auto TI = Ctx.getTypeInfo(Ty);
61 if (TI.isAlignRequired())
62 return TI.Align;
63
64 // MaxFieldAlignmentAttr is the attribute added to types
65 // declared after #pragma pack(n).
66 if (auto *Decl = Ty->getAsRecordDecl())
67 if (Decl->hasAttr<MaxFieldAlignmentAttr>())
68 return TI.Align;
69
70 return 0;
71}
72
73static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
74 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
75}
76
77static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
78 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
79}
80
81/// Returns true if \ref VD is a a holding variable (aka a
82/// VarDecl retrieved using \ref BindingDecl::getHoldingVar).
83static bool IsDecomposedVarDecl(VarDecl const *VD) {
84 auto const *Init = VD->getInit();
85 if (!Init)
86 return false;
87
88 auto const *RefExpr =
89 llvm::dyn_cast_or_null<DeclRefExpr>(Init->IgnoreUnlessSpelledInSource());
90 if (!RefExpr)
91 return false;
92
93 return llvm::dyn_cast_or_null<DecompositionDecl>(RefExpr->getDecl());
94}
95
96/// Returns true if \ref VD is a compiler-generated variable
97/// and should be treated as artificial for the purposes
98/// of debug-info generation.
99static bool IsArtificial(VarDecl const *VD) {
100 // Tuple-like bindings are marked as implicit despite
101 // being spelled out in source. Don't treat them as artificial
102 // variables.
103 if (IsDecomposedVarDecl(VD))
104 return false;
105
106 return VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
107 cast<Decl>(VD->getDeclContext())->isImplicit());
108}
109
111 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
112 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
113 DBuilder(CGM.getModule()) {
114 CreateCompileUnit();
115}
116
118 assert(LexicalBlockStack.empty() &&
119 "Region stack mismatch, stack not empty!");
120}
121
122ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
123 SourceLocation TemporaryLocation)
124 : CGF(&CGF) {
125 init(TemporaryLocation);
126}
127
128ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
129 bool DefaultToEmpty,
130 SourceLocation TemporaryLocation)
131 : CGF(&CGF) {
132 init(TemporaryLocation, DefaultToEmpty);
133}
134
135void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
136 bool DefaultToEmpty) {
137 auto *DI = CGF->getDebugInfo();
138 if (!DI) {
139 CGF = nullptr;
140 return;
141 }
142
143 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
144
145 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
146 return;
147
148 if (TemporaryLocation.isValid()) {
149 DI->EmitLocation(CGF->Builder, TemporaryLocation);
150 return;
151 }
152
153 if (DefaultToEmpty) {
154 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
155 return;
156 }
157
158 // Construct a location that has a valid scope, but no line info.
159 assert(!DI->LexicalBlockStack.empty());
160 CGF->Builder.SetCurrentDebugLocation(
161 llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
162 DI->LexicalBlockStack.back(), DI->getInlinedAt()));
163}
164
165ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
166 : CGF(&CGF) {
167 init(E->getExprLoc());
168}
169
170ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
171 : CGF(&CGF) {
172 if (!CGF.getDebugInfo()) {
173 this->CGF = nullptr;
174 return;
175 }
176 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
177 if (Loc)
178 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
179}
180
182 // Query CGF so the location isn't overwritten when location updates are
183 // temporarily disabled (for C++ default function arguments)
184 if (CGF)
185 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
186}
187
189 GlobalDecl InlinedFn)
190 : CGF(&CGF) {
191 if (!CGF.getDebugInfo()) {
192 this->CGF = nullptr;
193 return;
194 }
195 auto &DI = *CGF.getDebugInfo();
196 SavedLocation = DI.getLocation();
197 assert((DI.getInlinedAt() ==
198 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
199 "CGDebugInfo and IRBuilder are out of sync");
200
201 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
202}
203
205 if (!CGF)
206 return;
207 auto &DI = *CGF->getDebugInfo();
209 DI.EmitLocation(CGF->Builder, SavedLocation);
210}
211
213 // If the new location isn't valid return.
214 if (Loc.isInvalid())
215 return;
216
218
219 // If we've changed files in the middle of a lexical scope go ahead
220 // and create a new lexical scope with file node if it's different
221 // from the one in the scope.
222 if (LexicalBlockStack.empty())
223 return;
224
226 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
227 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
228 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
229 return;
230
231 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
232 LexicalBlockStack.pop_back();
233 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
234 LBF->getScope(), getOrCreateFile(CurLoc)));
235 } else if (isa<llvm::DILexicalBlock>(Scope) ||
236 isa<llvm::DISubprogram>(Scope)) {
237 LexicalBlockStack.pop_back();
238 LexicalBlockStack.emplace_back(
239 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
240 }
241}
242
243llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
244 llvm::DIScope *Mod = getParentModuleOrNull(D);
245 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
246 Mod ? Mod : TheCU);
247}
248
249llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
250 llvm::DIScope *Default) {
251 if (!Context)
252 return Default;
253
254 auto I = RegionMap.find(Context);
255 if (I != RegionMap.end()) {
256 llvm::Metadata *V = I->second;
257 return dyn_cast_or_null<llvm::DIScope>(V);
258 }
259
260 // Check namespace.
261 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
262 return getOrCreateNamespace(NSDecl);
263
264 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
265 if (!RDecl->isDependentType())
266 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
267 TheCU->getFile());
268 return Default;
269}
270
271PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
273
274 // If we're emitting codeview, it's important to try to match MSVC's naming so
275 // that visualizers written for MSVC will trigger for our class names. In
276 // particular, we can't have spaces between arguments of standard templates
277 // like basic_string and vector, but we must have spaces between consecutive
278 // angle brackets that close nested template argument lists.
279 if (CGM.getCodeGenOpts().EmitCodeView) {
280 PP.MSVCFormatting = true;
281 PP.SplitTemplateClosers = true;
282 } else {
283 // For DWARF, printing rules are underspecified.
284 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
285 PP.SplitTemplateClosers = true;
286 }
287
290 PP.PrintCanonicalTypes = true;
291 PP.UsePreferredNames = false;
293 PP.UseEnumerators = false;
294
295 // Apply -fdebug-prefix-map.
296 PP.Callbacks = &PrintCB;
297 return PP;
298}
299
300StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
301 return internString(GetName(FD));
302}
303
304StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
305 SmallString<256> MethodName;
306 llvm::raw_svector_ostream OS(MethodName);
307 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
308 const DeclContext *DC = OMD->getDeclContext();
309 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
310 OS << OID->getName();
311 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
312 OS << OID->getName();
313 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
314 if (OC->IsClassExtension()) {
315 OS << OC->getClassInterface()->getName();
316 } else {
317 OS << OC->getIdentifier()->getNameStart() << '('
318 << OC->getIdentifier()->getNameStart() << ')';
319 }
320 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
321 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
322 }
323 OS << ' ' << OMD->getSelector().getAsString() << ']';
324
325 return internString(OS.str());
326}
327
328StringRef CGDebugInfo::getSelectorName(Selector S) {
329 return internString(S.getAsString());
330}
331
332StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
333 if (isa<ClassTemplateSpecializationDecl>(RD)) {
334 // Copy this name on the side and use its reference.
335 return internString(GetName(RD));
336 }
337
338 // quick optimization to avoid having to intern strings that are already
339 // stored reliably elsewhere
340 if (const IdentifierInfo *II = RD->getIdentifier())
341 return II->getName();
342
343 // The CodeView printer in LLVM wants to see the names of unnamed types
344 // because they need to have a unique identifier.
345 // These names are used to reconstruct the fully qualified type names.
346 if (CGM.getCodeGenOpts().EmitCodeView) {
347 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
348 assert(RD->getDeclContext() == D->getDeclContext() &&
349 "Typedef should not be in another decl context!");
350 assert(D->getDeclName().getAsIdentifierInfo() &&
351 "Typedef was not named!");
352 return D->getDeclName().getAsIdentifierInfo()->getName();
353 }
354
355 if (CGM.getLangOpts().CPlusPlus) {
356 StringRef Name;
357
358 ASTContext &Context = CGM.getContext();
359 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
360 // Anonymous types without a name for linkage purposes have their
361 // declarator mangled in if they have one.
362 Name = DD->getName();
363 else if (const TypedefNameDecl *TND =
365 // Anonymous types without a name for linkage purposes have their
366 // associate typedef mangled in if they have one.
367 Name = TND->getName();
368
369 // Give lambdas a display name based on their name mangling.
370 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
371 if (CXXRD->isLambda())
372 return internString(
374
375 if (!Name.empty()) {
376 SmallString<256> UnnamedType("<unnamed-type-");
377 UnnamedType += Name;
378 UnnamedType += '>';
379 return internString(UnnamedType);
380 }
381 }
382 }
383
384 return StringRef();
385}
386
387std::optional<llvm::DIFile::ChecksumKind>
388CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
389 Checksum.clear();
390
391 if (!CGM.getCodeGenOpts().EmitCodeView &&
392 CGM.getCodeGenOpts().DwarfVersion < 5)
393 return std::nullopt;
394
396 std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
397 if (!MemBuffer)
398 return std::nullopt;
399
400 auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());
401 switch (CGM.getCodeGenOpts().getDebugSrcHash()) {
403 llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);
404 return llvm::DIFile::CSK_MD5;
406 llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);
407 return llvm::DIFile::CSK_SHA1;
409 llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);
410 return llvm::DIFile::CSK_SHA256;
411 }
412 llvm_unreachable("Unhandled DebugSrcHashKind enum");
413}
414
415std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
416 FileID FID) {
417 if (!CGM.getCodeGenOpts().EmbedSource)
418 return std::nullopt;
419
420 bool SourceInvalid = false;
421 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
422
423 if (SourceInvalid)
424 return std::nullopt;
425
426 return Source;
427}
428
429llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
431 StringRef FileName;
432 FileID FID;
433 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
434
435 if (Loc.isInvalid()) {
436 // The DIFile used by the CU is distinct from the main source file. Call
437 // createFile() below for canonicalization if the source file was specified
438 // with an absolute path.
439 FileName = TheCU->getFile()->getFilename();
440 CSInfo = TheCU->getFile()->getChecksum();
441 } else {
442 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
443 FileName = PLoc.getFilename();
444
445 if (FileName.empty()) {
446 FileName = TheCU->getFile()->getFilename();
447 } else {
448 FileName = PLoc.getFilename();
449 }
450 FID = PLoc.getFileID();
451 }
452
453 // Cache the results.
454 auto It = DIFileCache.find(FileName.data());
455 if (It != DIFileCache.end()) {
456 // Verify that the information still exists.
457 if (llvm::Metadata *V = It->second)
458 return cast<llvm::DIFile>(V);
459 }
460
461 // Put Checksum at a scope where it will persist past the createFile call.
462 SmallString<64> Checksum;
463 if (!CSInfo) {
464 std::optional<llvm::DIFile::ChecksumKind> CSKind =
465 computeChecksum(FID, Checksum);
466 if (CSKind)
467 CSInfo.emplace(*CSKind, Checksum);
468 }
469 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
470}
471
472llvm::DIFile *CGDebugInfo::createFile(
473 StringRef FileName,
474 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
475 std::optional<StringRef> Source) {
476 StringRef Dir;
477 StringRef File;
478 std::string RemappedFile = remapDIPath(FileName);
479 std::string CurDir = remapDIPath(getCurrentDirname());
480 SmallString<128> DirBuf;
481 SmallString<128> FileBuf;
482 if (llvm::sys::path::is_absolute(RemappedFile)) {
483 // Strip the common prefix (if it is more than just "/" or "C:\") from
484 // current directory and FileName for a more space-efficient encoding.
485 auto FileIt = llvm::sys::path::begin(RemappedFile);
486 auto FileE = llvm::sys::path::end(RemappedFile);
487 auto CurDirIt = llvm::sys::path::begin(CurDir);
488 auto CurDirE = llvm::sys::path::end(CurDir);
489 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
490 llvm::sys::path::append(DirBuf, *CurDirIt);
491 if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
492 // Don't strip the common prefix if it is only the root ("/" or "C:\")
493 // since that would make LLVM diagnostic locations confusing.
494 Dir = {};
495 File = RemappedFile;
496 } else {
497 for (; FileIt != FileE; ++FileIt)
498 llvm::sys::path::append(FileBuf, *FileIt);
499 Dir = DirBuf;
500 File = FileBuf;
501 }
502 } else {
503 if (!llvm::sys::path::is_absolute(FileName))
504 Dir = CurDir;
505 File = RemappedFile;
506 }
507 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
508 DIFileCache[FileName.data()].reset(F);
509 return F;
510}
511
512std::string CGDebugInfo::remapDIPath(StringRef Path) const {
514 for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))
515 if (llvm::sys::path::replace_path_prefix(P, From, To))
516 break;
517 return P.str().str();
518}
519
520unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
521 if (Loc.isInvalid())
522 return 0;
524 return SM.getPresumedLoc(Loc).getLine();
525}
526
527unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
528 // We may not want column information at all.
529 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
530 return 0;
531
532 // If the location is invalid then use the current column.
533 if (Loc.isInvalid() && CurLoc.isInvalid())
534 return 0;
536 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
537 return PLoc.isValid() ? PLoc.getColumn() : 0;
538}
539
540StringRef CGDebugInfo::getCurrentDirname() {
541 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
543
544 if (!CWDName.empty())
545 return CWDName;
546 llvm::ErrorOr<std::string> CWD =
547 CGM.getFileSystem()->getCurrentWorkingDirectory();
548 if (!CWD)
549 return StringRef();
550 return CWDName = internString(*CWD);
551}
552
553void CGDebugInfo::CreateCompileUnit() {
554 SmallString<64> Checksum;
555 std::optional<llvm::DIFile::ChecksumKind> CSKind;
556 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
557
558 // Should we be asking the SourceManager for the main file name, instead of
559 // accepting it as an argument? This just causes the main file name to
560 // mismatch with source locations and create extra lexical scopes or
561 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
562 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
563 // because that's what the SourceManager says)
564
565 // Get absolute path name.
567 auto &CGO = CGM.getCodeGenOpts();
568 const LangOptions &LO = CGM.getLangOpts();
569 std::string MainFileName = CGO.MainFileName;
570 if (MainFileName.empty())
571 MainFileName = "<stdin>";
572
573 // The main file name provided via the "-main-file-name" option contains just
574 // the file name itself with no path information. This file name may have had
575 // a relative path, so we look into the actual file entry for the main
576 // file to determine the real absolute path for the file.
577 std::string MainFileDir;
578 if (OptionalFileEntryRef MainFile =
579 SM.getFileEntryRefForID(SM.getMainFileID())) {
580 MainFileDir = std::string(MainFile->getDir().getName());
581 if (!llvm::sys::path::is_absolute(MainFileName)) {
582 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
583 llvm::sys::path::Style Style =
585 ? (CGM.getTarget().getTriple().isOSWindows()
586 ? llvm::sys::path::Style::windows_backslash
587 : llvm::sys::path::Style::posix)
588 : llvm::sys::path::Style::native;
589 llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
590 MainFileName = std::string(
591 llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
592 }
593 // If the main file name provided is identical to the input file name, and
594 // if the input file is a preprocessed source, use the module name for
595 // debug info. The module name comes from the name specified in the first
596 // linemarker if the input is a preprocessed source. In this case we don't
597 // know the content to compute a checksum.
598 if (MainFile->getName() == MainFileName &&
600 MainFile->getName().rsplit('.').second)
601 .isPreprocessed()) {
602 MainFileName = CGM.getModule().getName().str();
603 } else {
604 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
605 }
606 }
607
608 llvm::dwarf::SourceLanguage LangTag;
609 if (LO.CPlusPlus) {
610 if (LO.ObjC)
611 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
612 else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
613 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
614 else if (LO.CPlusPlus14)
615 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
616 else if (LO.CPlusPlus11)
617 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
618 else
619 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
620 } else if (LO.ObjC) {
621 LangTag = llvm::dwarf::DW_LANG_ObjC;
622 } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
623 CGM.getCodeGenOpts().DwarfVersion >= 5)) {
624 LangTag = llvm::dwarf::DW_LANG_OpenCL;
625 } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
626 LangTag = llvm::dwarf::DW_LANG_C11;
627 } else if (LO.C99) {
628 LangTag = llvm::dwarf::DW_LANG_C99;
629 } else {
630 LangTag = llvm::dwarf::DW_LANG_C89;
631 }
632
633 std::string Producer = getClangFullVersion();
634
635 // Figure out which version of the ObjC runtime we have.
636 unsigned RuntimeVers = 0;
637 if (LO.ObjC)
638 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
639
640 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
641 switch (DebugKind) {
642 case llvm::codegenoptions::NoDebugInfo:
643 case llvm::codegenoptions::LocTrackingOnly:
644 EmissionKind = llvm::DICompileUnit::NoDebug;
645 break;
646 case llvm::codegenoptions::DebugLineTablesOnly:
647 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
648 break;
649 case llvm::codegenoptions::DebugDirectivesOnly:
650 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
651 break;
652 case llvm::codegenoptions::DebugInfoConstructor:
653 case llvm::codegenoptions::LimitedDebugInfo:
654 case llvm::codegenoptions::FullDebugInfo:
655 case llvm::codegenoptions::UnusedTypeInfo:
656 EmissionKind = llvm::DICompileUnit::FullDebug;
657 break;
658 }
659
660 uint64_t DwoId = 0;
661 auto &CGOpts = CGM.getCodeGenOpts();
662 // The DIFile used by the CU is distinct from the main source
663 // file. Its directory part specifies what becomes the
664 // DW_AT_comp_dir (the compilation directory), even if the source
665 // file was specified with an absolute path.
666 if (CSKind)
667 CSInfo.emplace(*CSKind, Checksum);
668 llvm::DIFile *CUFile = DBuilder.createFile(
669 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
670 getSource(SM, SM.getMainFileID()));
671
672 StringRef Sysroot, SDK;
673 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
674 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
675 auto B = llvm::sys::path::rbegin(Sysroot);
676 auto E = llvm::sys::path::rend(Sysroot);
677 auto It =
678 std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });
679 if (It != E)
680 SDK = *It;
681 }
682
683 llvm::DICompileUnit::DebugNameTableKind NameTableKind =
684 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
685 CGOpts.DebugNameTable);
686 if (CGM.getTarget().getTriple().isNVPTX())
687 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;
688 else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
689 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;
690
691 // Create new compile unit.
692 TheCU = DBuilder.createCompileUnit(
693 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
694 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
695 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
696 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
697 NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
698}
699
700llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
701 llvm::dwarf::TypeKind Encoding;
702 StringRef BTName;
703 switch (BT->getKind()) {
704#define BUILTIN_TYPE(Id, SingletonId)
705#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
706#include "clang/AST/BuiltinTypes.def"
707 case BuiltinType::Dependent:
708 llvm_unreachable("Unexpected builtin type");
709 case BuiltinType::NullPtr:
710 return DBuilder.createNullPtrType();
711 case BuiltinType::Void:
712 return nullptr;
713 case BuiltinType::ObjCClass:
714 if (!ClassTy)
715 ClassTy =
716 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
717 "objc_class", TheCU, TheCU->getFile(), 0);
718 return ClassTy;
719 case BuiltinType::ObjCId: {
720 // typedef struct objc_class *Class;
721 // typedef struct objc_object {
722 // Class isa;
723 // } *id;
724
725 if (ObjTy)
726 return ObjTy;
727
728 if (!ClassTy)
729 ClassTy =
730 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
731 "objc_class", TheCU, TheCU->getFile(), 0);
732
733 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
734
735 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
736
737 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
738 0, 0, llvm::DINode::FlagZero, nullptr,
739 llvm::DINodeArray());
740
741 DBuilder.replaceArrays(
742 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
743 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
744 llvm::DINode::FlagZero, ISATy)));
745 return ObjTy;
746 }
747 case BuiltinType::ObjCSel: {
748 if (!SelTy)
749 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
750 "objc_selector", TheCU,
751 TheCU->getFile(), 0);
752 return SelTy;
753 }
754
755#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
756 case BuiltinType::Id: \
757 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
758 SingletonId);
759#include "clang/Basic/OpenCLImageTypes.def"
760 case BuiltinType::OCLSampler:
761 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
762 case BuiltinType::OCLEvent:
763 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
764 case BuiltinType::OCLClkEvent:
765 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
766 case BuiltinType::OCLQueue:
767 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
768 case BuiltinType::OCLReserveID:
769 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
770#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
771 case BuiltinType::Id: \
772 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
773#include "clang/Basic/OpenCLExtensionTypes.def"
774#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
775 case BuiltinType::Id: \
776 return getOrCreateStructPtrType(#Name, SingletonId);
777#include "clang/Basic/HLSLIntangibleTypes.def"
778
779#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
780#include "clang/Basic/AArch64SVEACLETypes.def"
781 {
782 if (BT->getKind() == BuiltinType::MFloat8) {
783 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
784 BTName = BT->getName(CGM.getLangOpts());
785 // Bit size and offset of the type.
787 return DBuilder.createBasicType(BTName, Size, Encoding);
788 }
790 // For svcount_t, only the lower 2 bytes are relevant.
791 BT->getKind() == BuiltinType::SveCount
793 CGM.getContext().BoolTy, llvm::ElementCount::getFixed(16),
794 1)
795 : CGM.getContext().getBuiltinVectorTypeInfo(BT);
796
797 // A single vector of bytes may not suffice as the representation of
798 // svcount_t tuples because of the gap between the active 16bits of
799 // successive tuple members. Currently no such tuples are defined for
800 // svcount_t, so assert that NumVectors is 1.
801 assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) &&
802 "Unsupported number of vectors for svcount_t");
803
804 // Debuggers can't extract 1bit from a vector, so will display a
805 // bitpattern for predicates instead.
806 unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors;
807 if (Info.ElementType == CGM.getContext().BoolTy) {
808 NumElems /= 8;
810 }
811
812 llvm::Metadata *LowerBound, *UpperBound;
813 LowerBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
814 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
815 if (Info.EC.isScalable()) {
816 unsigned NumElemsPerVG = NumElems / 2;
818 {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
819 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
820 llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
821 UpperBound = DBuilder.createExpression(Expr);
822 } else
823 UpperBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
824 llvm::Type::getInt64Ty(CGM.getLLVMContext()), NumElems - 1));
825
826 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
827 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
828 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
829 llvm::DIType *ElemTy =
830 getOrCreateType(Info.ElementType, TheCU->getFile());
831 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
832 return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
833 SubscriptArray);
834 }
835 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
836 // So we return a safe type here to avoid generating an error.
837#define PPC_VECTOR_TYPE(Name, Id, size) \
838 case BuiltinType::Id:
839#include "clang/Basic/PPCTypes.def"
840 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
841
842#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
843#include "clang/Basic/RISCVVTypes.def"
844 {
847
848 unsigned ElementCount = Info.EC.getKnownMinValue();
849 unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
850
851 bool Fractional = false;
852 unsigned LMUL;
853 unsigned FixedSize = ElementCount * SEW;
854 if (Info.ElementType == CGM.getContext().BoolTy) {
855 // Mask type only occupies one vector register.
856 LMUL = 1;
857 } else if (FixedSize < 64) {
858 // In RVV scalable vector types, we encode 64 bits in the fixed part.
859 Fractional = true;
860 LMUL = 64 / FixedSize;
861 } else {
862 LMUL = FixedSize / 64;
863 }
864
865 // Element count = (VLENB / SEW) x LMUL
867 // The DW_OP_bregx operation has two operands: a register which is
868 // specified by an unsigned LEB128 number, followed by a signed LEB128
869 // offset.
870 {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
871 4096 + 0xC22, // RISC-V VLENB CSR register.
872 0, // Offset for DW_OP_bregx. It is dummy here.
873 llvm::dwarf::DW_OP_constu,
874 SEW / 8, // SEW is in bits.
875 llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
876 if (Fractional)
877 Expr.push_back(llvm::dwarf::DW_OP_div);
878 else
879 Expr.push_back(llvm::dwarf::DW_OP_mul);
880 // Element max index = count - 1
881 Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
882
883 auto *LowerBound =
884 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
885 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
886 auto *UpperBound = DBuilder.createExpression(Expr);
887 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
888 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
889 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
890 llvm::DIType *ElemTy =
891 getOrCreateType(Info.ElementType, TheCU->getFile());
892
893 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
894 return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
895 SubscriptArray);
896 }
897
898#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
899 case BuiltinType::Id: { \
900 if (!SingletonId) \
901 SingletonId = \
902 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
903 MangledName, TheCU, TheCU->getFile(), 0); \
904 return SingletonId; \
905 }
906#include "clang/Basic/WebAssemblyReferenceTypes.def"
907#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
908 case BuiltinType::Id: { \
909 if (!SingletonId) \
910 SingletonId = \
911 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, \
912 TheCU, TheCU->getFile(), 0); \
913 return SingletonId; \
914 }
915#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
916 case BuiltinType::Id: { \
917 if (!SingletonId) \
918 SingletonId = \
919 DBuilder.createBasicType(Name, Width, llvm::dwarf::DW_ATE_unsigned); \
920 return SingletonId; \
921 }
922#include "clang/Basic/AMDGPUTypes.def"
923 case BuiltinType::UChar:
924 case BuiltinType::Char_U:
925 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
926 break;
927 case BuiltinType::Char_S:
928 case BuiltinType::SChar:
929 Encoding = llvm::dwarf::DW_ATE_signed_char;
930 break;
931 case BuiltinType::Char8:
932 case BuiltinType::Char16:
933 case BuiltinType::Char32:
934 Encoding = llvm::dwarf::DW_ATE_UTF;
935 break;
936 case BuiltinType::UShort:
937 case BuiltinType::UInt:
938 case BuiltinType::UInt128:
939 case BuiltinType::ULong:
940 case BuiltinType::WChar_U:
941 case BuiltinType::ULongLong:
942 Encoding = llvm::dwarf::DW_ATE_unsigned;
943 break;
944 case BuiltinType::Short:
945 case BuiltinType::Int:
946 case BuiltinType::Int128:
947 case BuiltinType::Long:
948 case BuiltinType::WChar_S:
949 case BuiltinType::LongLong:
950 Encoding = llvm::dwarf::DW_ATE_signed;
951 break;
952 case BuiltinType::Bool:
953 Encoding = llvm::dwarf::DW_ATE_boolean;
954 break;
955 case BuiltinType::Half:
956 case BuiltinType::Float:
957 case BuiltinType::LongDouble:
958 case BuiltinType::Float16:
959 case BuiltinType::BFloat16:
960 case BuiltinType::Float128:
961 case BuiltinType::Double:
962 case BuiltinType::Ibm128:
963 // FIXME: For targets where long double, __ibm128 and __float128 have the
964 // same size, they are currently indistinguishable in the debugger without
965 // some special treatment. However, there is currently no consensus on
966 // encoding and this should be updated once a DWARF encoding exists for
967 // distinct floating point types of the same size.
968 Encoding = llvm::dwarf::DW_ATE_float;
969 break;
970 case BuiltinType::ShortAccum:
971 case BuiltinType::Accum:
972 case BuiltinType::LongAccum:
973 case BuiltinType::ShortFract:
974 case BuiltinType::Fract:
975 case BuiltinType::LongFract:
976 case BuiltinType::SatShortFract:
977 case BuiltinType::SatFract:
978 case BuiltinType::SatLongFract:
979 case BuiltinType::SatShortAccum:
980 case BuiltinType::SatAccum:
981 case BuiltinType::SatLongAccum:
982 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
983 break;
984 case BuiltinType::UShortAccum:
985 case BuiltinType::UAccum:
986 case BuiltinType::ULongAccum:
987 case BuiltinType::UShortFract:
988 case BuiltinType::UFract:
989 case BuiltinType::ULongFract:
990 case BuiltinType::SatUShortAccum:
991 case BuiltinType::SatUAccum:
992 case BuiltinType::SatULongAccum:
993 case BuiltinType::SatUShortFract:
994 case BuiltinType::SatUFract:
995 case BuiltinType::SatULongFract:
996 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
997 break;
998 }
999
1000 BTName = BT->getName(CGM.getLangOpts());
1001 // Bit size and offset of the type.
1002 uint64_t Size = CGM.getContext().getTypeSize(BT);
1003 return DBuilder.createBasicType(BTName, Size, Encoding);
1004}
1005
1006llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
1007
1008 StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
1009 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
1010 ? llvm::dwarf::DW_ATE_unsigned
1011 : llvm::dwarf::DW_ATE_signed;
1012
1013 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
1014 Encoding);
1015}
1016
1017llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
1018 // Bit size and offset of the type.
1019 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
1020 if (Ty->isComplexIntegerType())
1021 Encoding = llvm::dwarf::DW_ATE_lo_user;
1022
1023 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1024 return DBuilder.createBasicType("complex", Size, Encoding);
1025}
1026
1028 // Ignore these qualifiers for now.
1029 Q.removeObjCGCAttr();
1032 Q.removeUnaligned();
1033}
1034
1035static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
1036 if (Q.hasConst()) {
1037 Q.removeConst();
1038 return llvm::dwarf::DW_TAG_const_type;
1039 }
1040 if (Q.hasVolatile()) {
1041 Q.removeVolatile();
1042 return llvm::dwarf::DW_TAG_volatile_type;
1043 }
1044 if (Q.hasRestrict()) {
1045 Q.removeRestrict();
1046 return llvm::dwarf::DW_TAG_restrict_type;
1047 }
1048 return (llvm::dwarf::Tag)0;
1049}
1050
1051llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
1052 llvm::DIFile *Unit) {
1054 const Type *T = Qc.strip(Ty);
1055
1057
1058 // We will create one Derived type for one qualifier and recurse to handle any
1059 // additional ones.
1060 llvm::dwarf::Tag Tag = getNextQualifier(Qc);
1061 if (!Tag) {
1062 assert(Qc.empty() && "Unknown type qualifier for debug info");
1063 return getOrCreateType(QualType(T, 0), Unit);
1064 }
1065
1066 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
1067
1068 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1069 // CVR derived types.
1070 return DBuilder.createQualifiedType(Tag, FromTy);
1071}
1072
1073llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
1074 llvm::DIFile *Unit) {
1076 Qualifiers &Q = EPI.TypeQuals;
1078
1079 // We will create one Derived type for one qualifier and recurse to handle any
1080 // additional ones.
1081 llvm::dwarf::Tag Tag = getNextQualifier(Q);
1082 if (!Tag) {
1083 assert(Q.empty() && "Unknown type qualifier for debug info");
1084 return nullptr;
1085 }
1086
1087 auto *FromTy =
1088 getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
1089 F->getParamTypes(), EPI),
1090 Unit);
1091
1092 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1093 // CVR derived types.
1094 return DBuilder.createQualifiedType(Tag, FromTy);
1095}
1096
1097llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1098 llvm::DIFile *Unit) {
1099
1100 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1101 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1102 // debug info, we want to emit 'id' in both cases.
1103 if (Ty->isObjCQualifiedIdType())
1104 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1105
1106 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1107 Ty->getPointeeType(), Unit);
1108}
1109
1110llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
1111 llvm::DIFile *Unit) {
1112 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1113 Ty->getPointeeType(), Unit);
1114}
1115
1116/// \return whether a C++ mangling exists for the type defined by TD.
1117static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1118 switch (TheCU->getSourceLanguage()) {
1119 case llvm::dwarf::DW_LANG_C_plus_plus:
1120 case llvm::dwarf::DW_LANG_C_plus_plus_11:
1121 case llvm::dwarf::DW_LANG_C_plus_plus_14:
1122 return true;
1123 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1124 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1125 default:
1126 return false;
1127 }
1128}
1129
1130// Determines if the debug info for this tag declaration needs a type
1131// identifier. The purpose of the unique identifier is to deduplicate type
1132// information for identical types across TUs. Because of the C++ one definition
1133// rule (ODR), it is valid to assume that the type is defined the same way in
1134// every TU and its debug info is equivalent.
1135//
1136// C does not have the ODR, and it is common for codebases to contain multiple
1137// different definitions of a struct with the same name in different TUs.
1138// Therefore, if the type doesn't have a C++ mangling, don't give it an
1139// identifer. Type information in C is smaller and simpler than C++ type
1140// information, so the increase in debug info size is negligible.
1141//
1142// If the type is not externally visible, it should be unique to the current TU,
1143// and should not need an identifier to participate in type deduplication.
1144// However, when emitting CodeView, the format internally uses these
1145// unique type name identifers for references between debug info. For example,
1146// the method of a class in an anonymous namespace uses the identifer to refer
1147// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1148// for such types, so when emitting CodeView, always use identifiers for C++
1149// types. This may create problems when attempting to emit CodeView when the MS
1150// C++ ABI is not in use.
1151static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1152 llvm::DICompileUnit *TheCU) {
1153 // We only add a type identifier for types with C++ name mangling.
1154 if (!hasCXXMangling(TD, TheCU))
1155 return false;
1156
1157 // Externally visible types with C++ mangling need a type identifier.
1158 if (TD->isExternallyVisible())
1159 return true;
1160
1161 // CodeView types with C++ mangling need a type identifier.
1162 if (CGM.getCodeGenOpts().EmitCodeView)
1163 return true;
1164
1165 return false;
1166}
1167
1168// Returns a unique type identifier string if one exists, or an empty string.
1170 llvm::DICompileUnit *TheCU) {
1172 const TagDecl *TD = Ty->getDecl();
1173
1174 if (!needsTypeIdentifier(TD, CGM, TheCU))
1175 return Identifier;
1176 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1177 if (RD->getDefinition())
1178 if (RD->isDynamicClass() &&
1179 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1180 return Identifier;
1181
1182 // TODO: This is using the RTTI name. Is there a better way to get
1183 // a unique string for a type?
1184 llvm::raw_svector_ostream Out(Identifier);
1186 return Identifier;
1187}
1188
1189/// \return the appropriate DWARF tag for a composite type.
1190static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1191 llvm::dwarf::Tag Tag;
1192 if (RD->isStruct() || RD->isInterface())
1193 Tag = llvm::dwarf::DW_TAG_structure_type;
1194 else if (RD->isUnion())
1195 Tag = llvm::dwarf::DW_TAG_union_type;
1196 else {
1197 // FIXME: This could be a struct type giving a default visibility different
1198 // than C++ class type, but needs llvm metadata changes first.
1199 assert(RD->isClass());
1200 Tag = llvm::dwarf::DW_TAG_class_type;
1201 }
1202 return Tag;
1203}
1204
1205llvm::DICompositeType *
1206CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1207 llvm::DIScope *Ctx) {
1208 const RecordDecl *RD = Ty->getDecl();
1209 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1210 return cast<llvm::DICompositeType>(T);
1211 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1212 const unsigned Line =
1213 getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1214 StringRef RDName = getClassName(RD);
1215
1216 uint64_t Size = 0;
1217 uint32_t Align = 0;
1218
1219 const RecordDecl *D = RD->getDefinition();
1220 if (D && D->isCompleteDefinition())
1221 Size = CGM.getContext().getTypeSize(Ty);
1222
1223 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1224
1225 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1226 // add the flag if a record has no definition because we don't know whether
1227 // it will be trivial or not.
1228 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1229 if (!CXXRD->hasDefinition() ||
1230 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1231 Flags |= llvm::DINode::FlagNonTrivial;
1232
1233 // Create the type.
1235 // Don't include a linkage name in line tables only.
1237 Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1238 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1239 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1240 Identifier);
1241 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1242 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1243 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1244 CollectCXXTemplateParams(TSpecial, DefUnit));
1245 ReplaceMap.emplace_back(
1246 std::piecewise_construct, std::make_tuple(Ty),
1247 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1248 return RetTy;
1249}
1250
1251llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1252 const Type *Ty,
1253 QualType PointeeTy,
1254 llvm::DIFile *Unit) {
1255 // Bit size, align and offset of the type.
1256 // Size is always the size of a pointer.
1257 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1258 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1259 std::optional<unsigned> DWARFAddressSpace =
1261 CGM.getTypes().getTargetAddressSpace(PointeeTy));
1262
1263 const BTFTagAttributedType *BTFAttrTy;
1264 if (auto *Atomic = PointeeTy->getAs<AtomicType>())
1265 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Atomic->getValueType());
1266 else
1267 BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1269 while (BTFAttrTy) {
1270 StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1271 if (!Tag.empty()) {
1272 llvm::Metadata *Ops[2] = {
1273 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1274 llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1275 Annots.insert(Annots.begin(),
1276 llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1277 }
1278 BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1279 }
1280
1281 llvm::DINodeArray Annotations = nullptr;
1282 if (Annots.size() > 0)
1283 Annotations = DBuilder.getOrCreateArray(Annots);
1284
1285 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1286 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1287 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1288 Size, Align, DWARFAddressSpace);
1289 else
1290 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1291 Align, DWARFAddressSpace, StringRef(),
1292 Annotations);
1293}
1294
1295llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1296 llvm::DIType *&Cache) {
1297 if (Cache)
1298 return Cache;
1299 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1300 TheCU, TheCU->getFile(), 0);
1301 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1302 Cache = DBuilder.createPointerType(Cache, Size);
1303 return Cache;
1304}
1305
1306uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1307 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1308 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1309 QualType FType;
1310
1311 // Advanced by calls to CreateMemberType in increments of FType, then
1312 // returned as the overall size of the default elements.
1313 uint64_t FieldOffset = 0;
1314
1315 // Blocks in OpenCL have unique constraints which make the standard fields
1316 // redundant while requiring size and align fields for enqueue_kernel. See
1317 // initializeForBlockHeader in CGBlocks.cpp
1318 if (CGM.getLangOpts().OpenCL) {
1319 FType = CGM.getContext().IntTy;
1320 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1321 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1322 } else {
1323 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1324 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1325 FType = CGM.getContext().IntTy;
1326 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1327 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1328 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1329 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1330 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1331 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1332 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1333 EltTys.push_back(DBuilder.createMemberType(
1334 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1335 FieldOffset, llvm::DINode::FlagZero, DescTy));
1336 FieldOffset += FieldSize;
1337 }
1338
1339 return FieldOffset;
1340}
1341
1342llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1343 llvm::DIFile *Unit) {
1345 QualType FType;
1346 uint64_t FieldOffset;
1347 llvm::DINodeArray Elements;
1348
1349 FieldOffset = 0;
1350 FType = CGM.getContext().UnsignedLongTy;
1351 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1352 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1353
1354 Elements = DBuilder.getOrCreateArray(EltTys);
1355 EltTys.clear();
1356
1357 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1358
1359 auto *EltTy =
1360 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1361 FieldOffset, 0, Flags, nullptr, Elements);
1362
1363 // Bit size, align and offset of the type.
1364 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1365
1366 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1367
1368 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1369 0, EltTys);
1370
1371 Elements = DBuilder.getOrCreateArray(EltTys);
1372
1373 // The __block_literal_generic structs are marked with a special
1374 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1375 // the debugger needs to know about. To allow type uniquing, emit
1376 // them without a name or a location.
1377 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1378 Flags, nullptr, Elements);
1379
1380 return DBuilder.createPointerType(EltTy, Size);
1381}
1382
1385 assert(Ty->isTypeAlias());
1386 // TemplateSpecializationType doesn't know if its template args are
1387 // being substituted into a parameter pack. We can find out if that's
1388 // the case now by inspecting the TypeAliasTemplateDecl template
1389 // parameters. Insert Ty's template args into SpecArgs, bundling args
1390 // passed to a parameter pack into a TemplateArgument::Pack. It also
1391 // doesn't know the value of any defaulted args, so collect those now
1392 // too.
1394 ArrayRef SubstArgs = Ty->template_arguments();
1395 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1396 // If Param is a parameter pack, pack the remaining arguments.
1397 if (Param->isParameterPack()) {
1398 SpecArgs.push_back(TemplateArgument(SubstArgs));
1399 break;
1400 }
1401
1402 // Skip defaulted args.
1403 // FIXME: Ideally, we wouldn't do this. We can read the default values
1404 // for each parameter. However, defaulted arguments which are dependent
1405 // values or dependent types can't (easily?) be resolved here.
1406 if (SubstArgs.empty()) {
1407 // If SubstArgs is now empty (we're taking from it each iteration) and
1408 // this template parameter isn't a pack, then that should mean we're
1409 // using default values for the remaining template parameters (after
1410 // which there may be an empty pack too which we will ignore).
1411 break;
1412 }
1413
1414 // Take the next argument.
1415 SpecArgs.push_back(SubstArgs.front());
1416 SubstArgs = SubstArgs.drop_front();
1417 }
1418 return SpecArgs;
1419}
1420
1421llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1422 llvm::DIFile *Unit) {
1423 assert(Ty->isTypeAlias());
1424 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1425
1427 if (isa<BuiltinTemplateDecl>(TD))
1428 return Src;
1429
1430 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1431 if (AliasDecl->hasAttr<NoDebugAttr>())
1432 return Src;
1433
1435 llvm::raw_svector_ostream OS(NS);
1436
1437 auto PP = getPrintingPolicy();
1439
1440 SourceLocation Loc = AliasDecl->getLocation();
1441
1442 if (CGM.getCodeGenOpts().DebugTemplateAlias &&
1443 // FIXME: This is a workaround for the issue
1444 // https://github.com/llvm/llvm-project/issues/89774
1445 // The TemplateSpecializationType doesn't contain any instantiation
1446 // information; dependent template arguments can't be resolved. For now,
1447 // fall back to DW_TAG_typedefs for template aliases that are
1448 // instantiation dependent, e.g.:
1449 // ```
1450 // template <int>
1451 // using A = int;
1452 //
1453 // template<int I>
1454 // struct S {
1455 // using AA = A<I>; // Instantiation dependent.
1456 // AA aa;
1457 // };
1458 //
1459 // S<0> s;
1460 // ```
1461 // S::AA's underlying type A<I> is dependent on I so will be emitted as a
1462 // DW_TAG_typedef.
1464 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1465 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1466
1467 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1468 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1469 // doesn't have instantiation information, so
1470 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1471 // template args.
1472 std::string Name;
1473 llvm::raw_string_ostream OS(Name);
1474 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1475 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1476 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1477 !HasReconstitutableArgs(Args.Args))
1478 printTemplateArgumentList(OS, Args.Args, PP);
1479
1480 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1481 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1482 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1483 return AliasTy;
1484 }
1485
1487 TD->getTemplateParameters());
1488 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1489 getLineNumber(Loc),
1490 getDeclContextDescriptor(AliasDecl));
1491}
1492
1493/// Convert an AccessSpecifier into the corresponding DINode flag.
1494/// As an optimization, return 0 if the access specifier equals the
1495/// default for the containing type.
1496static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1497 const RecordDecl *RD) {
1499 if (RD && RD->isClass())
1501 else if (RD && (RD->isStruct() || RD->isUnion()))
1503
1504 if (Access == Default)
1505 return llvm::DINode::FlagZero;
1506
1507 switch (Access) {
1508 case clang::AS_private:
1509 return llvm::DINode::FlagPrivate;
1511 return llvm::DINode::FlagProtected;
1512 case clang::AS_public:
1513 return llvm::DINode::FlagPublic;
1514 case clang::AS_none:
1515 return llvm::DINode::FlagZero;
1516 }
1517 llvm_unreachable("unexpected access enumerator");
1518}
1519
1520llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1521 llvm::DIFile *Unit) {
1522 llvm::DIType *Underlying =
1523 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1524
1525 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1526 return Underlying;
1527
1528 // We don't set size information, but do specify where the typedef was
1529 // declared.
1531
1532 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1533 // Typedefs are derived from some other type.
1534 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1535
1536 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1537 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1538 if (isa<RecordDecl>(DC))
1539 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1540
1541 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1542 getOrCreateFile(Loc), getLineNumber(Loc),
1543 getDeclContextDescriptor(Ty->getDecl()), Align,
1544 Flags, Annotations);
1545}
1546
1547static unsigned getDwarfCC(CallingConv CC) {
1548 switch (CC) {
1549 case CC_C:
1550 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1551 return 0;
1552
1553 case CC_X86StdCall:
1554 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1555 case CC_X86FastCall:
1556 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1557 case CC_X86ThisCall:
1558 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1559 case CC_X86VectorCall:
1560 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1561 case CC_X86Pascal:
1562 return llvm::dwarf::DW_CC_BORLAND_pascal;
1563 case CC_Win64:
1564 return llvm::dwarf::DW_CC_LLVM_Win64;
1565 case CC_X86_64SysV:
1566 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1567 case CC_AAPCS:
1569 case CC_AArch64SVEPCS:
1570 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1571 case CC_AAPCS_VFP:
1572 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1573 case CC_IntelOclBicc:
1574 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1575 case CC_SpirFunction:
1576 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1577 case CC_OpenCLKernel:
1579 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1580 case CC_Swift:
1581 return llvm::dwarf::DW_CC_LLVM_Swift;
1582 case CC_SwiftAsync:
1583 return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1584 case CC_PreserveMost:
1585 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1586 case CC_PreserveAll:
1587 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1588 case CC_X86RegCall:
1589 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1590 case CC_M68kRTD:
1591 return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1592 case CC_PreserveNone:
1593 return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1594 case CC_RISCVVectorCall:
1595 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1596 }
1597 return 0;
1598}
1599
1600static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1601 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1602 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1603 Flags |= llvm::DINode::FlagLValueReference;
1604 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1605 Flags |= llvm::DINode::FlagRValueReference;
1606 return Flags;
1607}
1608
1609llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1610 llvm::DIFile *Unit) {
1611 const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1612 if (FPT) {
1613 if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1614 return QTy;
1615 }
1616
1617 // Create the type without any qualifiers
1618
1620
1621 // Add the result type at least.
1622 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1623
1624 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1625 // Set up remainder of arguments if there is a prototype.
1626 // otherwise emit it as a variadic function.
1627 if (!FPT) {
1628 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1629 } else {
1630 Flags = getRefFlags(FPT);
1631 for (const QualType &ParamType : FPT->param_types())
1632 EltTys.push_back(getOrCreateType(ParamType, Unit));
1633 if (FPT->isVariadic())
1634 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1635 }
1636
1637 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1638 llvm::DIType *F = DBuilder.createSubroutineType(
1639 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1640 return F;
1641}
1642
1643llvm::DIDerivedType *
1644CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1645 llvm::DIScope *RecordTy, const RecordDecl *RD) {
1646 StringRef Name = BitFieldDecl->getName();
1647 QualType Ty = BitFieldDecl->getType();
1648 if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1649 Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1650 SourceLocation Loc = BitFieldDecl->getLocation();
1651 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1652 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1653
1654 // Get the location for the field.
1655 llvm::DIFile *File = getOrCreateFile(Loc);
1656 unsigned Line = getLineNumber(Loc);
1657
1658 const CGBitFieldInfo &BitFieldInfo =
1659 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1660 uint64_t SizeInBits = BitFieldInfo.Size;
1661 assert(SizeInBits > 0 && "found named 0-width bitfield");
1662 uint64_t StorageOffsetInBits =
1663 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1664 uint64_t Offset = BitFieldInfo.Offset;
1665 // The bit offsets for big endian machines are reversed for big
1666 // endian target, compensate for that as the DIDerivedType requires
1667 // un-reversed offsets.
1668 if (CGM.getDataLayout().isBigEndian())
1669 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1670 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1671 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1672 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1673 return DBuilder.createBitFieldMemberType(
1674 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1675 Flags, DebugType, Annotations);
1676}
1677
1678llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1679 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1680 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1681
1683 return nullptr;
1684
1685 /*
1686 Add a *single* zero-bitfield separator between two non-zero bitfields
1687 separated by one or more zero-bitfields. This is used to distinguish between
1688 structures such the ones below, where the memory layout is the same, but how
1689 the ABI assigns fields to registers differs.
1690
1691 struct foo {
1692 int space[4];
1693 char a : 8; // on amdgpu, passed on v4
1694 char b : 8;
1695 char x : 8;
1696 char y : 8;
1697 };
1698 struct bar {
1699 int space[4];
1700 char a : 8; // on amdgpu, passed on v4
1701 char b : 8;
1702 char : 0;
1703 char x : 8; // passed on v5
1704 char y : 8;
1705 };
1706 */
1707 if (PreviousFieldsDI.empty())
1708 return nullptr;
1709
1710 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1711 auto *PreviousMDEntry =
1712 PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1713 auto *PreviousMDField =
1714 dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1715 if (!PreviousMDField || !PreviousMDField->isBitField() ||
1716 PreviousMDField->getSizeInBits() == 0)
1717 return nullptr;
1718
1719 auto PreviousBitfield = RD->field_begin();
1720 std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1721
1722 assert(PreviousBitfield->isBitField());
1723
1724 ASTContext &Context = CGM.getContext();
1725 if (!PreviousBitfield->isZeroLengthBitField(Context))
1726 return nullptr;
1727
1728 QualType Ty = PreviousBitfield->getType();
1729 SourceLocation Loc = PreviousBitfield->getLocation();
1730 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1731 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1732 llvm::DIScope *RecordTy = BitFieldDI->getScope();
1733
1734 llvm::DIFile *File = getOrCreateFile(Loc);
1735 unsigned Line = getLineNumber(Loc);
1736
1737 uint64_t StorageOffsetInBits =
1738 cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1739 ->getZExtValue();
1740
1741 llvm::DINode::DIFlags Flags =
1742 getAccessFlag(PreviousBitfield->getAccess(), RD);
1743 llvm::DINodeArray Annotations =
1744 CollectBTFDeclTagAnnotations(*PreviousBitfield);
1745 return DBuilder.createBitFieldMemberType(
1746 RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
1747 Flags, DebugType, Annotations);
1748}
1749
1750llvm::DIType *CGDebugInfo::createFieldType(
1751 StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1752 uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1753 llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1754 llvm::DIType *debugType = getOrCreateType(type, tunit);
1755
1756 // Get the location for the field.
1757 llvm::DIFile *file = getOrCreateFile(loc);
1758 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1759
1760 uint64_t SizeInBits = 0;
1761 auto Align = AlignInBits;
1762 if (!type->isIncompleteArrayType()) {
1763 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1764 SizeInBits = TI.Width;
1765 if (!Align)
1766 Align = getTypeAlignIfRequired(type, CGM.getContext());
1767 }
1768
1769 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1770 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1771 offsetInBits, flags, debugType, Annotations);
1772}
1773
1774llvm::DISubprogram *
1775CGDebugInfo::createInlinedTrapSubprogram(StringRef FuncName,
1776 llvm::DIFile *FileScope) {
1777 // We are caching the subprogram because we don't want to duplicate
1778 // subprograms with the same message. Note that `SPFlagDefinition` prevents
1779 // subprograms from being uniqued.
1780 llvm::DISubprogram *&SP = InlinedTrapFuncMap[FuncName];
1781
1782 if (!SP) {
1783 llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(nullptr);
1784 SP = DBuilder.createFunction(
1785 /*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(),
1786 /*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy,
1787 /*ScopeLine=*/0,
1788 /*Flags=*/llvm::DINode::FlagArtificial,
1789 /*SPFlags=*/llvm::DISubprogram::SPFlagDefinition,
1790 /*TParams=*/nullptr, /*ThrownTypes=*/nullptr, /*Annotations=*/nullptr);
1791 }
1792
1793 return SP;
1794}
1795
1796void CGDebugInfo::CollectRecordLambdaFields(
1797 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1798 llvm::DIType *RecordTy) {
1799 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1800 // has the name and the location of the variable so we should iterate over
1801 // both concurrently.
1802 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1804 unsigned fieldno = 0;
1806 E = CXXDecl->captures_end();
1807 I != E; ++I, ++Field, ++fieldno) {
1808 const LambdaCapture &C = *I;
1809 if (C.capturesVariable()) {
1810 SourceLocation Loc = C.getLocation();
1811 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1812 ValueDecl *V = C.getCapturedVar();
1813 StringRef VName = V->getName();
1814 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1815 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1816 llvm::DIType *FieldType = createFieldType(
1817 VName, Field->getType(), Loc, Field->getAccess(),
1818 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1819 elements.push_back(FieldType);
1820 } else if (C.capturesThis()) {
1821 // TODO: Need to handle 'this' in some way by probably renaming the
1822 // this of the lambda class and having a field member of 'this' or
1823 // by using AT_object_pointer for the function and having that be
1824 // used as 'this' for semantic references.
1825 FieldDecl *f = *Field;
1826 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1827 QualType type = f->getType();
1828 StringRef ThisName =
1829 CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
1830 llvm::DIType *fieldType = createFieldType(
1831 ThisName, type, f->getLocation(), f->getAccess(),
1832 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1833
1834 elements.push_back(fieldType);
1835 }
1836 }
1837}
1838
1839llvm::DIDerivedType *
1840CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1841 const RecordDecl *RD) {
1842 // Create the descriptor for the static variable, with or without
1843 // constant initializers.
1844 Var = Var->getCanonicalDecl();
1845 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1846 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1847
1848 unsigned LineNumber = getLineNumber(Var->getLocation());
1849 StringRef VName = Var->getName();
1850
1851 // FIXME: to avoid complications with type merging we should
1852 // emit the constant on the definition instead of the declaration.
1853 llvm::Constant *C = nullptr;
1854 if (Var->getInit()) {
1855 const APValue *Value = Var->evaluateValue();
1856 if (Value) {
1857 if (Value->isInt())
1858 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1859 if (Value->isFloat())
1860 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1861 }
1862 }
1863
1864 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1865 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
1866 ? llvm::dwarf::DW_TAG_variable
1867 : llvm::dwarf::DW_TAG_member;
1868 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1869 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1870 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
1871 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1872 return GV;
1873}
1874
1875void CGDebugInfo::CollectRecordNormalField(
1876 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1877 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1878 const RecordDecl *RD) {
1879 StringRef name = field->getName();
1880 QualType type = field->getType();
1881
1882 // Ignore unnamed fields unless they're anonymous structs/unions.
1883 if (name.empty() && !type->isRecordType())
1884 return;
1885
1886 llvm::DIType *FieldType;
1887 if (field->isBitField()) {
1888 llvm::DIDerivedType *BitFieldType;
1889 FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
1890 if (llvm::DIType *Separator =
1891 createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
1892 elements.push_back(Separator);
1893 } else {
1894 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1895 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1896 FieldType =
1897 createFieldType(name, type, field->getLocation(), field->getAccess(),
1898 OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1899 }
1900
1901 elements.push_back(FieldType);
1902}
1903
1904void CGDebugInfo::CollectRecordNestedType(
1905 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1906 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1907 // Injected class names are not considered nested records.
1908 if (isa<InjectedClassNameType>(Ty))
1909 return;
1911 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1912 elements.push_back(nestedType);
1913}
1914
1915void CGDebugInfo::CollectRecordFields(
1916 const RecordDecl *record, llvm::DIFile *tunit,
1918 llvm::DICompositeType *RecordTy) {
1919 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1920
1921 if (CXXDecl && CXXDecl->isLambda())
1922 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1923 else {
1924 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1925
1926 // Field number for non-static fields.
1927 unsigned fieldNo = 0;
1928
1929 // Static and non-static members should appear in the same order as
1930 // the corresponding declarations in the source program.
1931 for (const auto *I : record->decls())
1932 if (const auto *V = dyn_cast<VarDecl>(I)) {
1933 if (V->hasAttr<NoDebugAttr>())
1934 continue;
1935
1936 // Skip variable template specializations when emitting CodeView. MSVC
1937 // doesn't emit them.
1938 if (CGM.getCodeGenOpts().EmitCodeView &&
1939 isa<VarTemplateSpecializationDecl>(V))
1940 continue;
1941
1942 if (isa<VarTemplatePartialSpecializationDecl>(V))
1943 continue;
1944
1945 // Reuse the existing static member declaration if one exists
1946 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1947 if (MI != StaticDataMemberCache.end()) {
1948 assert(MI->second &&
1949 "Static data member declaration should still exist");
1950 elements.push_back(MI->second);
1951 } else {
1952 auto Field = CreateRecordStaticField(V, RecordTy, record);
1953 elements.push_back(Field);
1954 }
1955 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1956 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1957 elements, RecordTy, record);
1958
1959 // Bump field number for next field.
1960 ++fieldNo;
1961 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1962 // Debug info for nested types is included in the member list only for
1963 // CodeView.
1964 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
1965 // MSVC doesn't generate nested type for anonymous struct/union.
1966 if (isa<RecordDecl>(I) &&
1967 cast<RecordDecl>(I)->isAnonymousStructOrUnion())
1968 continue;
1969 if (!nestedType->isImplicit() &&
1970 nestedType->getDeclContext() == record)
1971 CollectRecordNestedType(nestedType, elements);
1972 }
1973 }
1974 }
1975}
1976
1977llvm::DISubroutineType *
1978CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1979 llvm::DIFile *Unit) {
1980 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1981 if (Method->isStatic())
1982 return cast_or_null<llvm::DISubroutineType>(
1983 getOrCreateType(QualType(Func, 0), Unit));
1984
1985 QualType ThisType;
1987 ThisType = Method->getThisType();
1988
1989 return getOrCreateInstanceMethodType(ThisType, Func, Unit);
1990}
1991
1992llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1993 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1994 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1995 Qualifiers &Qc = EPI.TypeQuals;
1996 Qc.removeConst();
1997 Qc.removeVolatile();
1998 Qc.removeRestrict();
1999 Qc.removeUnaligned();
2000 // Keep the removed qualifiers in sync with
2001 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
2002 // On a 'real' member function type, these qualifiers are carried on the type
2003 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
2004 // tags around them. (But, in the raw function types with qualifiers, they have
2005 // to use wrapper types.)
2006
2007 // Add "this" pointer.
2008 const auto *OriginalFunc = cast<llvm::DISubroutineType>(
2009 getOrCreateType(CGM.getContext().getFunctionType(
2010 Func->getReturnType(), Func->getParamTypes(), EPI),
2011 Unit));
2012 llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
2013 assert(Args.size() && "Invalid number of arguments!");
2014
2016
2017 // First element is always return type. For 'void' functions it is NULL.
2018 Elts.push_back(Args[0]);
2019
2020 // "this" pointer is always first argument.
2021 // ThisPtr may be null if the member function has an explicit 'this'
2022 // parameter.
2023 if (!ThisPtr.isNull()) {
2024 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
2025 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2026 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
2027 Elts.push_back(ThisPtrType);
2028 }
2029
2030 // Copy rest of the arguments.
2031 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2032 Elts.push_back(Args[i]);
2033
2034 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2035
2036 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
2037 getDwarfCC(Func->getCallConv()));
2038}
2039
2040/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
2041/// inside a function.
2042static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
2043 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
2044 return isFunctionLocalClass(NRD);
2045 if (isa<FunctionDecl>(RD->getDeclContext()))
2046 return true;
2047 return false;
2048}
2049
2050llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
2051 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
2052 bool IsCtorOrDtor =
2053 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
2054
2055 StringRef MethodName = getFunctionName(Method);
2056 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
2057
2058 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
2059 // make sense to give a single ctor/dtor a linkage name.
2060 StringRef MethodLinkageName;
2061 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
2062 // property to use here. It may've been intended to model "is non-external
2063 // type" but misses cases of non-function-local but non-external classes such
2064 // as those in anonymous namespaces as well as the reverse - external types
2065 // that are function local, such as those in (non-local) inline functions.
2066 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
2067 MethodLinkageName = CGM.getMangledName(Method);
2068
2069 // Get the location for the method.
2070 llvm::DIFile *MethodDefUnit = nullptr;
2071 unsigned MethodLine = 0;
2072 if (!Method->isImplicit()) {
2073 MethodDefUnit = getOrCreateFile(Method->getLocation());
2074 MethodLine = getLineNumber(Method->getLocation());
2075 }
2076
2077 // Collect virtual method info.
2078 llvm::DIType *ContainingType = nullptr;
2079 unsigned VIndex = 0;
2080 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2081 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2082 int ThisAdjustment = 0;
2083
2085 if (Method->isPureVirtual())
2086 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2087 else
2088 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2089
2090 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2091 // It doesn't make sense to give a virtual destructor a vtable index,
2092 // since a single destructor has two entries in the vtable.
2093 if (!isa<CXXDestructorDecl>(Method))
2094 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2095 } else {
2096 // Emit MS ABI vftable information. There is only one entry for the
2097 // deleting dtor.
2098 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2099 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
2102 VIndex = ML.Index;
2103
2104 // CodeView only records the vftable offset in the class that introduces
2105 // the virtual method. This is possible because, unlike Itanium, the MS
2106 // C++ ABI does not include all virtual methods from non-primary bases in
2107 // the vtable for the most derived class. For example, if C inherits from
2108 // A and B, C's primary vftable will not include B's virtual methods.
2109 if (Method->size_overridden_methods() == 0)
2110 Flags |= llvm::DINode::FlagIntroducedVirtual;
2111
2112 // The 'this' adjustment accounts for both the virtual and non-virtual
2113 // portions of the adjustment. Presumably the debugger only uses it when
2114 // it knows the dynamic type of an object.
2117 .getQuantity();
2118 }
2119 ContainingType = RecordTy;
2120 }
2121
2122 if (Method->getCanonicalDecl()->isDeleted())
2123 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2124
2125 if (Method->isNoReturn())
2126 Flags |= llvm::DINode::FlagNoReturn;
2127
2128 if (Method->isStatic())
2129 Flags |= llvm::DINode::FlagStaticMember;
2130 if (Method->isImplicit())
2131 Flags |= llvm::DINode::FlagArtificial;
2132 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2133 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2134 if (CXXC->isExplicit())
2135 Flags |= llvm::DINode::FlagExplicit;
2136 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2137 if (CXXC->isExplicit())
2138 Flags |= llvm::DINode::FlagExplicit;
2139 }
2140 if (Method->hasPrototype())
2141 Flags |= llvm::DINode::FlagPrototyped;
2142 if (Method->getRefQualifier() == RQ_LValue)
2143 Flags |= llvm::DINode::FlagLValueReference;
2144 if (Method->getRefQualifier() == RQ_RValue)
2145 Flags |= llvm::DINode::FlagRValueReference;
2146 if (!Method->isExternallyVisible())
2147 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2148 if (CGM.getLangOpts().Optimize)
2149 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2150
2151 // In this debug mode, emit type info for a class when its constructor type
2152 // info is emitted.
2153 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2154 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2155 completeUnusedClass(*CD->getParent());
2156
2157 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2158 llvm::DISubprogram *SP = DBuilder.createMethod(
2159 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2160 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2161 TParamsArray.get());
2162
2163 SPCache[Method->getCanonicalDecl()].reset(SP);
2164
2165 return SP;
2166}
2167
2168void CGDebugInfo::CollectCXXMemberFunctions(
2169 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2170 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2171
2172 // Since we want more than just the individual member decls if we
2173 // have templated functions iterate over every declaration to gather
2174 // the functions.
2175 for (const auto *I : RD->decls()) {
2176 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2177 // If the member is implicit, don't add it to the member list. This avoids
2178 // the member being added to type units by LLVM, while still allowing it
2179 // to be emitted into the type declaration/reference inside the compile
2180 // unit.
2181 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2182 // FIXME: Handle Using(Shadow?)Decls here to create
2183 // DW_TAG_imported_declarations inside the class for base decls brought into
2184 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2185 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2186 // referenced)
2187 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2188 continue;
2189
2191 continue;
2192
2193 // Reuse the existing member function declaration if it exists.
2194 // It may be associated with the declaration of the type & should be
2195 // reused as we're building the definition.
2196 //
2197 // This situation can arise in the vtable-based debug info reduction where
2198 // implicit members are emitted in a non-vtable TU.
2199 auto MI = SPCache.find(Method->getCanonicalDecl());
2200 EltTys.push_back(MI == SPCache.end()
2201 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2202 : static_cast<llvm::Metadata *>(MI->second));
2203 }
2204}
2205
2206void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2208 llvm::DIType *RecordTy) {
2209 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
2210 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2211 llvm::DINode::FlagZero);
2212
2213 // If we are generating CodeView debug info, we also need to emit records for
2214 // indirect virtual base classes.
2215 if (CGM.getCodeGenOpts().EmitCodeView) {
2216 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2217 llvm::DINode::FlagIndirectVirtualBase);
2218 }
2219}
2220
2221void CGDebugInfo::CollectCXXBasesAux(
2222 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2223 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2225 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2226 llvm::DINode::DIFlags StartingFlags) {
2227 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2228 for (const auto &BI : Bases) {
2229 const auto *Base =
2230 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
2231 if (!SeenTypes.insert(Base).second)
2232 continue;
2233 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2234 llvm::DINode::DIFlags BFlags = StartingFlags;
2235 uint64_t BaseOffset;
2236 uint32_t VBPtrOffset = 0;
2237
2238 if (BI.isVirtual()) {
2239 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2240 // virtual base offset offset is -ve. The code generator emits dwarf
2241 // expression where it expects +ve number.
2242 BaseOffset = 0 - CGM.getItaniumVTableContext()
2244 .getQuantity();
2245 } else {
2246 // In the MS ABI, store the vbtable offset, which is analogous to the
2247 // vbase offset offset in Itanium.
2248 BaseOffset =
2250 VBPtrOffset = CGM.getContext()
2253 .getQuantity();
2254 }
2255 BFlags |= llvm::DINode::FlagVirtual;
2256 } else
2257 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2258 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2259 // BI->isVirtual() and bits when not.
2260
2261 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2262 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2263 VBPtrOffset, BFlags);
2264 EltTys.push_back(DTy);
2265 }
2266}
2267
2268llvm::DINodeArray
2269CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2270 llvm::DIFile *Unit) {
2271 if (!OArgs)
2272 return llvm::DINodeArray();
2273 TemplateArgs &Args = *OArgs;
2274 SmallVector<llvm::Metadata *, 16> TemplateParams;
2275 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2276 const TemplateArgument &TA = Args.Args[i];
2277 StringRef Name;
2278 const bool defaultParameter = TA.getIsDefaulted();
2279 if (Args.TList)
2280 Name = Args.TList->getParam(i)->getName();
2281
2282 switch (TA.getKind()) {
2284 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2285 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2286 TheCU, Name, TTy, defaultParameter));
2287
2288 } break;
2290 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2291 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2292 TheCU, Name, TTy, defaultParameter,
2293 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2294 } break;
2296 const ValueDecl *D = TA.getAsDecl();
2298 llvm::DIType *TTy = getOrCreateType(T, Unit);
2299 llvm::Constant *V = nullptr;
2300 // Skip retrieve the value if that template parameter has cuda device
2301 // attribute, i.e. that value is not available at the host side.
2302 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2303 !D->hasAttr<CUDADeviceAttr>()) {
2304 // Variable pointer template parameters have a value that is the address
2305 // of the variable.
2306 if (const auto *VD = dyn_cast<VarDecl>(D))
2307 V = CGM.GetAddrOfGlobalVar(VD);
2308 // Member function pointers have special support for building them,
2309 // though this is currently unsupported in LLVM CodeGen.
2310 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2311 MD && MD->isImplicitObjectMemberFunction())
2313 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2314 V = CGM.GetAddrOfFunction(FD);
2315 // Member data pointers have special handling too to compute the fixed
2316 // offset within the object.
2317 else if (const auto *MPT =
2318 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2319 // These five lines (& possibly the above member function pointer
2320 // handling) might be able to be refactored to use similar code in
2321 // CodeGenModule::getMemberPointerConstant
2322 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2323 CharUnits chars =
2324 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2325 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2326 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2327 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2328 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2329 if (T->isRecordType())
2331 SourceLocation(), TPO->getValue(), TPO->getType());
2332 else
2334 }
2335 assert(V && "Failed to find template parameter pointer");
2336 V = V->stripPointerCasts();
2337 }
2338 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2339 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2340 } break;
2342 QualType T = TA.getNullPtrType();
2343 llvm::DIType *TTy = getOrCreateType(T, Unit);
2344 llvm::Constant *V = nullptr;
2345 // Special case member data pointer null values since they're actually -1
2346 // instead of zero.
2347 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2348 // But treat member function pointers as simple zero integers because
2349 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2350 // CodeGen grows handling for values of non-null member function
2351 // pointers then perhaps we could remove this special case and rely on
2352 // EmitNullMemberPointer for member function pointers.
2353 if (MPT->isMemberDataPointer())
2354 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2355 if (!V)
2356 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2357 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2358 TheCU, Name, TTy, defaultParameter, V));
2359 } break;
2362 llvm::DIType *TTy = getOrCreateType(T, Unit);
2363 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2365 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2366 TheCU, Name, TTy, defaultParameter, V));
2367 } break;
2369 std::string QualName;
2370 llvm::raw_string_ostream OS(QualName);
2372 OS, getPrintingPolicy());
2373 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2374 TheCU, Name, nullptr, QualName, defaultParameter));
2375 break;
2376 }
2378 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2379 TheCU, Name, nullptr,
2380 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2381 break;
2383 const Expr *E = TA.getAsExpr();
2384 QualType T = E->getType();
2385 if (E->isGLValue())
2387 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2388 assert(V && "Expression in template argument isn't constant");
2389 llvm::DIType *TTy = getOrCreateType(T, Unit);
2390 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2391 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2392 } break;
2393 // And the following should never occur:
2396 llvm_unreachable(
2397 "These argument types shouldn't exist in concrete types");
2398 }
2399 }
2400 return DBuilder.getOrCreateArray(TemplateParams);
2401}
2402
2403std::optional<CGDebugInfo::TemplateArgs>
2404CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2405 if (FD->getTemplatedKind() ==
2408 ->getTemplate()
2410 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2411 }
2412 return std::nullopt;
2413}
2414std::optional<CGDebugInfo::TemplateArgs>
2415CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2416 // Always get the full list of parameters, not just the ones from the
2417 // specialization. A partial specialization may have fewer parameters than
2418 // there are arguments.
2419 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2420 if (!TS)
2421 return std::nullopt;
2422 VarTemplateDecl *T = TS->getSpecializedTemplate();
2423 const TemplateParameterList *TList = T->getTemplateParameters();
2424 auto TA = TS->getTemplateArgs().asArray();
2425 return {{TList, TA}};
2426}
2427std::optional<CGDebugInfo::TemplateArgs>
2428CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2429 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2430 // Always get the full list of parameters, not just the ones from the
2431 // specialization. A partial specialization may have fewer parameters than
2432 // there are arguments.
2433 TemplateParameterList *TPList =
2434 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2435 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2436 return {{TPList, TAList.asArray()}};
2437 }
2438 return std::nullopt;
2439}
2440
2441llvm::DINodeArray
2442CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2443 llvm::DIFile *Unit) {
2444 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2445}
2446
2447llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2448 llvm::DIFile *Unit) {
2449 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2450}
2451
2452llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2453 llvm::DIFile *Unit) {
2454 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2455}
2456
2457llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2458 if (!D->hasAttr<BTFDeclTagAttr>())
2459 return nullptr;
2460
2462 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2463 llvm::Metadata *Ops[2] = {
2464 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2465 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2466 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2467 }
2468 return DBuilder.getOrCreateArray(Annotations);
2469}
2470
2471llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2472 if (VTablePtrType)
2473 return VTablePtrType;
2474
2475 ASTContext &Context = CGM.getContext();
2476
2477 /* Function type */
2478 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2479 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2480 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2481 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2482 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2483 std::optional<unsigned> DWARFAddressSpace =
2484 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2485
2486 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2487 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2488 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2489 return VTablePtrType;
2490}
2491
2492StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2493 // Copy the gdb compatible name on the side and use its reference.
2494 return internString("_vptr$", RD->getNameAsString());
2495}
2496
2497StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2498 DynamicInitKind StubKind,
2499 llvm::Function *InitFn) {
2500 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2501 // arbitrary.
2502 if (!CGM.getCodeGenOpts().EmitCodeView ||
2504 return InitFn->getName();
2505
2506 // Print the normal qualified name for the variable, then break off the last
2507 // NNS, and add the appropriate other text. Clang always prints the global
2508 // variable name without template arguments, so we can use rsplit("::") and
2509 // then recombine the pieces.
2510 SmallString<128> QualifiedGV;
2511 StringRef Quals;
2512 StringRef GVName;
2513 {
2514 llvm::raw_svector_ostream OS(QualifiedGV);
2515 VD->printQualifiedName(OS, getPrintingPolicy());
2516 std::tie(Quals, GVName) = OS.str().rsplit("::");
2517 if (GVName.empty())
2518 std::swap(Quals, GVName);
2519 }
2520
2521 SmallString<128> InitName;
2522 llvm::raw_svector_ostream OS(InitName);
2523 if (!Quals.empty())
2524 OS << Quals << "::";
2525
2526 switch (StubKind) {
2529 llvm_unreachable("not an initializer");
2531 OS << "`dynamic initializer for '";
2532 break;
2534 OS << "`dynamic atexit destructor for '";
2535 break;
2536 }
2537
2538 OS << GVName;
2539
2540 // Add any template specialization args.
2541 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2542 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2543 getPrintingPolicy());
2544 }
2545
2546 OS << '\'';
2547
2548 return internString(OS.str());
2549}
2550
2551void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2553 // If this class is not dynamic then there is not any vtable info to collect.
2554 if (!RD->isDynamicClass())
2555 return;
2556
2557 // Don't emit any vtable shape or vptr info if this class doesn't have an
2558 // extendable vfptr. This can happen if the class doesn't have virtual
2559 // methods, or in the MS ABI if those virtual methods only come from virtually
2560 // inherited bases.
2561 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2562 if (!RL.hasExtendableVFPtr())
2563 return;
2564
2565 // CodeView needs to know how large the vtable of every dynamic class is, so
2566 // emit a special named pointer type into the element list. The vptr type
2567 // points to this type as well.
2568 llvm::DIType *VPtrTy = nullptr;
2569 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2571 if (NeedVTableShape) {
2572 uint64_t PtrWidth =
2574 const VTableLayout &VFTLayout =
2576 unsigned VSlotCount =
2577 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2578 unsigned VTableWidth = PtrWidth * VSlotCount;
2579 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2580 std::optional<unsigned> DWARFAddressSpace =
2581 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2582
2583 // Create a very wide void* type and insert it directly in the element list.
2584 llvm::DIType *VTableType = DBuilder.createPointerType(
2585 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2586 EltTys.push_back(VTableType);
2587
2588 // The vptr is a pointer to this special vtable type.
2589 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2590 }
2591
2592 // If there is a primary base then the artificial vptr member lives there.
2593 if (RL.getPrimaryBase())
2594 return;
2595
2596 if (!VPtrTy)
2597 VPtrTy = getOrCreateVTablePtrType(Unit);
2598
2599 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2600 llvm::DIType *VPtrMember =
2601 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2602 llvm::DINode::FlagArtificial, VPtrTy);
2603 EltTys.push_back(VPtrMember);
2604}
2605
2608 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2609 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2610 return T;
2611}
2612
2616}
2617
2620 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2621 assert(!D.isNull() && "null type");
2622 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2623 assert(T && "could not create debug info for type");
2624
2625 RetainedTypes.push_back(D.getAsOpaquePtr());
2626 return T;
2627}
2628
2630 QualType AllocatedTy,
2632 if (CGM.getCodeGenOpts().getDebugInfo() <=
2633 llvm::codegenoptions::DebugLineTablesOnly)
2634 return;
2635 llvm::MDNode *node;
2636 if (AllocatedTy->isVoidType())
2637 node = llvm::MDNode::get(CGM.getLLVMContext(), {});
2638 else
2639 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2640
2641 CI->setMetadata("heapallocsite", node);
2642}
2643
2645 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2646 return;
2647 QualType Ty = CGM.getContext().getEnumType(ED);
2648 void *TyPtr = Ty.getAsOpaquePtr();
2649 auto I = TypeCache.find(TyPtr);
2650 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2651 return;
2652 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2653 assert(!Res->isForwardDecl());
2654 TypeCache[TyPtr].reset(Res);
2655}
2656
2658 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2659 !CGM.getLangOpts().CPlusPlus)
2661}
2662
2663/// Return true if the class or any of its methods are marked dllimport.
2665 if (RD->hasAttr<DLLImportAttr>())
2666 return true;
2667 for (const CXXMethodDecl *MD : RD->methods())
2668 if (MD->hasAttr<DLLImportAttr>())
2669 return true;
2670 return false;
2671}
2672
2673/// Does a type definition exist in an imported clang module?
2674static bool isDefinedInClangModule(const RecordDecl *RD) {
2675 // Only definitions that where imported from an AST file come from a module.
2676 if (!RD || !RD->isFromASTFile())
2677 return false;
2678 // Anonymous entities cannot be addressed. Treat them as not from module.
2679 if (!RD->isExternallyVisible() && RD->getName().empty())
2680 return false;
2681 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2682 if (!CXXDecl->isCompleteDefinition())
2683 return false;
2684 // Check wether RD is a template.
2685 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2686 if (TemplateKind != TSK_Undeclared) {
2687 // Unfortunately getOwningModule() isn't accurate enough to find the
2688 // owning module of a ClassTemplateSpecializationDecl that is inside a
2689 // namespace spanning multiple modules.
2690 bool Explicit = false;
2691 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2692 Explicit = TD->isExplicitInstantiationOrSpecialization();
2693 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2694 return false;
2695 // This is a template, check the origin of the first member.
2696 if (CXXDecl->field_begin() == CXXDecl->field_end())
2697 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2698 if (!CXXDecl->field_begin()->isFromASTFile())
2699 return false;
2700 }
2701 }
2702 return true;
2703}
2704
2706 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2707 if (CXXRD->isDynamicClass() &&
2708 CGM.getVTableLinkage(CXXRD) ==
2709 llvm::GlobalValue::AvailableExternallyLinkage &&
2711 return;
2712
2713 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2714 return;
2715
2716 completeClass(RD);
2717}
2718
2720 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2721 return;
2722 QualType Ty = CGM.getContext().getRecordType(RD);
2723 void *TyPtr = Ty.getAsOpaquePtr();
2724 auto I = TypeCache.find(TyPtr);
2725 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2726 return;
2727
2728 // We want the canonical definition of the structure to not
2729 // be the typedef. Since that would lead to circular typedef
2730 // metadata.
2731 auto [Res, PrefRes] = CreateTypeDefinition(Ty->castAs<RecordType>());
2732 assert(!Res->isForwardDecl());
2733 TypeCache[TyPtr].reset(Res);
2734}
2735
2738 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2740 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2741 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2742 return true;
2743 return false;
2744}
2745
2746static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2747 // Constructor homing can be used for classes that cannnot be constructed
2748 // without emitting code for one of their constructors. This is classes that
2749 // don't have trivial or constexpr constructors, or can be created from
2750 // aggregate initialization. Also skip lambda objects because they don't call
2751 // constructors.
2752
2753 // Skip this optimization if the class or any of its methods are marked
2754 // dllimport.
2756 return false;
2757
2758 if (RD->isLambda() || RD->isAggregate() ||
2761 return false;
2762
2763 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
2764 if (Ctor->isCopyOrMoveConstructor())
2765 continue;
2766 if (!Ctor->isDeleted())
2767 return true;
2768 }
2769 return false;
2770}
2771
2772static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
2773 bool DebugTypeExtRefs, const RecordDecl *RD,
2774 const LangOptions &LangOpts) {
2775 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2776 return true;
2777
2778 if (auto *ES = RD->getASTContext().getExternalSource())
2779 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2780 return true;
2781
2782 // Only emit forward declarations in line tables only to keep debug info size
2783 // small. This only applies to CodeView, since we don't emit types in DWARF
2784 // line tables only.
2785 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
2786 return true;
2787
2788 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2789 RD->hasAttr<StandaloneDebugAttr>())
2790 return false;
2791
2792 if (!LangOpts.CPlusPlus)
2793 return false;
2794
2796 return true;
2797
2798 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2799
2800 if (!CXXDecl)
2801 return false;
2802
2803 // Only emit complete debug info for a dynamic class when its vtable is
2804 // emitted. However, Microsoft debuggers don't resolve type information
2805 // across DLL boundaries, so skip this optimization if the class or any of its
2806 // methods are marked dllimport. This isn't a complete solution, since objects
2807 // without any dllimport methods can be used in one DLL and constructed in
2808 // another, but it is the current behavior of LimitedDebugInfo.
2809 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2810 !isClassOrMethodDLLImport(CXXDecl))
2811 return true;
2812
2814 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2815 Spec = SD->getSpecializationKind();
2816
2819 CXXDecl->method_end()))
2820 return true;
2821
2822 // In constructor homing mode, only emit complete debug info for a class
2823 // when its constructor is emitted.
2824 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
2825 canUseCtorHoming(CXXDecl))
2826 return true;
2827
2828 return false;
2829}
2830
2832 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2833 return;
2834
2835 QualType Ty = CGM.getContext().getRecordType(RD);
2836 llvm::DIType *T = getTypeOrNull(Ty);
2837 if (T && T->isForwardDecl())
2839}
2840
2841llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2842 RecordDecl *RD = Ty->getDecl();
2843 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2844 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2845 CGM.getLangOpts())) {
2846 if (!T)
2847 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2848 return T;
2849 }
2850
2851 auto [Def, Pref] = CreateTypeDefinition(Ty);
2852
2853 return Pref ? Pref : Def;
2854}
2855
2856llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
2857 llvm::DIFile *Unit) {
2858 if (!RD)
2859 return nullptr;
2860
2861 auto const *PNA = RD->getAttr<PreferredNameAttr>();
2862 if (!PNA)
2863 return nullptr;
2864
2865 return getOrCreateType(PNA->getTypedefType(), Unit);
2866}
2867
2868std::pair<llvm::DIType *, llvm::DIType *>
2869CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2870 RecordDecl *RD = Ty->getDecl();
2871
2872 // Get overall information about the record type for the debug info.
2873 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2874
2875 // Records and classes and unions can all be recursive. To handle them, we
2876 // first generate a debug descriptor for the struct as a forward declaration.
2877 // Then (if it is a definition) we go through and get debug info for all of
2878 // its members. Finally, we create a descriptor for the complete type (which
2879 // may refer to the forward decl if the struct is recursive) and replace all
2880 // uses of the forward declaration with the final definition.
2881 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2882
2883 const RecordDecl *D = RD->getDefinition();
2884 if (!D || !D->isCompleteDefinition())
2885 return {FwdDecl, nullptr};
2886
2887 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2888 CollectContainingType(CXXDecl, FwdDecl);
2889
2890 // Push the struct on region stack.
2891 LexicalBlockStack.emplace_back(&*FwdDecl);
2892 RegionMap[Ty->getDecl()].reset(FwdDecl);
2893
2894 // Convert all the elements.
2896 // what about nested types?
2897
2898 // Note: The split of CXXDecl information here is intentional, the
2899 // gdb tests will depend on a certain ordering at printout. The debug
2900 // information offsets are still correct if we merge them all together
2901 // though.
2902 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2903 if (CXXDecl) {
2904 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2905 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2906 }
2907
2908 // Collect data fields (including static variables and any initializers).
2909 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2910 if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)
2911 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2912
2913 LexicalBlockStack.pop_back();
2914 RegionMap.erase(Ty->getDecl());
2915
2916 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2917 DBuilder.replaceArrays(FwdDecl, Elements);
2918
2919 if (FwdDecl->isTemporary())
2920 FwdDecl =
2921 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2922
2923 RegionMap[Ty->getDecl()].reset(FwdDecl);
2924
2925 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
2926 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
2927 return {FwdDecl, PrefDI};
2928
2929 return {FwdDecl, nullptr};
2930}
2931
2932llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2933 llvm::DIFile *Unit) {
2934 // Ignore protocols.
2935 return getOrCreateType(Ty->getBaseType(), Unit);
2936}
2937
2938llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2939 llvm::DIFile *Unit) {
2940 // Ignore protocols.
2942
2943 // Use Typedefs to represent ObjCTypeParamType.
2944 return DBuilder.createTypedef(
2945 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2946 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2947 getDeclContextDescriptor(Ty->getDecl()));
2948}
2949
2950/// \return true if Getter has the default name for the property PD.
2952 const ObjCMethodDecl *Getter) {
2953 assert(PD);
2954 if (!Getter)
2955 return true;
2956
2957 assert(Getter->getDeclName().isObjCZeroArgSelector());
2958 return PD->getName() ==
2960}
2961
2962/// \return true if Setter has the default name for the property PD.
2964 const ObjCMethodDecl *Setter) {
2965 assert(PD);
2966 if (!Setter)
2967 return true;
2968
2969 assert(Setter->getDeclName().isObjCOneArgSelector());
2972}
2973
2974llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2975 llvm::DIFile *Unit) {
2976 ObjCInterfaceDecl *ID = Ty->getDecl();
2977 if (!ID)
2978 return nullptr;
2979
2980 auto RuntimeLang =
2981 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2982
2983 // Return a forward declaration if this type was imported from a clang module,
2984 // and this is not the compile unit with the implementation of the type (which
2985 // may contain hidden ivars).
2986 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2987 !ID->getImplementation())
2988 return DBuilder.createForwardDecl(
2989 llvm::dwarf::DW_TAG_structure_type, ID->getName(),
2990 getDeclContextDescriptor(ID), Unit, 0, RuntimeLang);
2991
2992 // Get overall information about the record type for the debug info.
2993 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2994 unsigned Line = getLineNumber(ID->getLocation());
2995
2996 // If this is just a forward declaration return a special forward-declaration
2997 // debug type since we won't be able to lay out the entire type.
2998 ObjCInterfaceDecl *Def = ID->getDefinition();
2999 if (!Def || !Def->getImplementation()) {
3000 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3001 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
3002 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
3003 DefUnit, Line, RuntimeLang);
3004 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
3005 return FwdDecl;
3006 }
3007
3008 return CreateTypeDefinition(Ty, Unit);
3009}
3010
3011llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
3012 bool CreateSkeletonCU) {
3013 // Use the Module pointer as the key into the cache. This is a
3014 // nullptr if the "Module" is a PCH, which is safe because we don't
3015 // support chained PCH debug info, so there can only be a single PCH.
3016 const Module *M = Mod.getModuleOrNull();
3017 auto ModRef = ModuleCache.find(M);
3018 if (ModRef != ModuleCache.end())
3019 return cast<llvm::DIModule>(ModRef->second);
3020
3021 // Macro definitions that were defined with "-D" on the command line.
3022 SmallString<128> ConfigMacros;
3023 {
3024 llvm::raw_svector_ostream OS(ConfigMacros);
3025 const auto &PPOpts = CGM.getPreprocessorOpts();
3026 unsigned I = 0;
3027 // Translate the macro definitions back into a command line.
3028 for (auto &M : PPOpts.Macros) {
3029 if (++I > 1)
3030 OS << " ";
3031 const std::string &Macro = M.first;
3032 bool Undef = M.second;
3033 OS << "\"-" << (Undef ? 'U' : 'D');
3034 for (char c : Macro)
3035 switch (c) {
3036 case '\\':
3037 OS << "\\\\";
3038 break;
3039 case '"':
3040 OS << "\\\"";
3041 break;
3042 default:
3043 OS << c;
3044 }
3045 OS << '\"';
3046 }
3047 }
3048
3049 bool IsRootModule = M ? !M->Parent : true;
3050 // When a module name is specified as -fmodule-name, that module gets a
3051 // clang::Module object, but it won't actually be built or imported; it will
3052 // be textual.
3053 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3054 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3055 "clang module without ASTFile must be specified by -fmodule-name");
3056
3057 // Return a StringRef to the remapped Path.
3058 auto RemapPath = [this](StringRef Path) -> std::string {
3059 std::string Remapped = remapDIPath(Path);
3060 StringRef Relative(Remapped);
3061 StringRef CompDir = TheCU->getDirectory();
3062 if (Relative.consume_front(CompDir))
3063 Relative.consume_front(llvm::sys::path::get_separator());
3064
3065 return Relative.str();
3066 };
3067
3068 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3069 // PCH files don't have a signature field in the control block,
3070 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3071 // We use the lower 64 bits for debug info.
3072
3073 uint64_t Signature = 0;
3074 if (const auto &ModSig = Mod.getSignature())
3075 Signature = ModSig.truncatedValue();
3076 else
3077 Signature = ~1ULL;
3078
3079 llvm::DIBuilder DIB(CGM.getModule());
3080 SmallString<0> PCM;
3081 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3083 PCM = getCurrentDirname();
3084 else
3085 PCM = Mod.getPath();
3086 }
3087 llvm::sys::path::append(PCM, Mod.getASTFile());
3088 DIB.createCompileUnit(
3089 TheCU->getSourceLanguage(),
3090 // TODO: Support "Source" from external AST providers?
3091 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3092 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3093 llvm::DICompileUnit::FullDebug, Signature);
3094 DIB.finalize();
3095 }
3096
3097 llvm::DIModule *Parent =
3098 IsRootModule ? nullptr
3099 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3100 CreateSkeletonCU);
3101 std::string IncludePath = Mod.getPath().str();
3102 llvm::DIModule *DIMod =
3103 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3104 RemapPath(IncludePath));
3105 ModuleCache[M].reset(DIMod);
3106 return DIMod;
3107}
3108
3109llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3110 llvm::DIFile *Unit) {
3111 ObjCInterfaceDecl *ID = Ty->getDecl();
3112 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3113 unsigned Line = getLineNumber(ID->getLocation());
3114 unsigned RuntimeLang = TheCU->getSourceLanguage();
3115
3116 // Bit size, align and offset of the type.
3117 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3118 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3119
3120 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3121 if (ID->getImplementation())
3122 Flags |= llvm::DINode::FlagObjcClassComplete;
3123
3124 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3125 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3126 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3127 nullptr, llvm::DINodeArray(), RuntimeLang);
3128
3129 QualType QTy(Ty, 0);
3130 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3131
3132 // Push the struct on region stack.
3133 LexicalBlockStack.emplace_back(RealDecl);
3134 RegionMap[Ty->getDecl()].reset(RealDecl);
3135
3136 // Convert all the elements.
3138
3139 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3140 if (SClass) {
3141 llvm::DIType *SClassTy =
3142 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3143 if (!SClassTy)
3144 return nullptr;
3145
3146 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3147 llvm::DINode::FlagZero);
3148 EltTys.push_back(InhTag);
3149 }
3150
3151 // Create entries for all of the properties.
3152 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3153 SourceLocation Loc = PD->getLocation();
3154 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3155 unsigned PLine = getLineNumber(Loc);
3156 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3157 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3158 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3159 PD->getName(), PUnit, PLine,
3160 hasDefaultGetterName(PD, Getter) ? ""
3161 : getSelectorName(PD->getGetterName()),
3162 hasDefaultSetterName(PD, Setter) ? ""
3163 : getSelectorName(PD->getSetterName()),
3164 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3165 EltTys.push_back(PropertyNode);
3166 };
3167 {
3168 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3169 // empty/tombstone keys in the data type (and bool is too small for that).
3170 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3171 /// List of already emitted properties. Two distinct class and instance
3172 /// properties can share the same identifier (but not two instance
3173 /// properties or two class properties).
3174 llvm::DenseSet<IsClassAndIdent> PropertySet;
3175 /// Returns the IsClassAndIdent key for the given property.
3176 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3177 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3178 };
3179 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3180 for (auto *PD : ClassExt->properties()) {
3181 PropertySet.insert(GetIsClassAndIdent(PD));
3182 AddProperty(PD);
3183 }
3184 for (const auto *PD : ID->properties()) {
3185 // Don't emit duplicate metadata for properties that were already in a
3186 // class extension.
3187 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3188 continue;
3189 AddProperty(PD);
3190 }
3191 }
3192
3194 unsigned FieldNo = 0;
3195 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3196 Field = Field->getNextIvar(), ++FieldNo) {
3197 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3198 if (!FieldTy)
3199 return nullptr;
3200
3201 StringRef FieldName = Field->getName();
3202
3203 // Ignore unnamed fields.
3204 if (FieldName.empty())
3205 continue;
3206
3207 // Get the location for the field.
3208 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3209 unsigned FieldLine = getLineNumber(Field->getLocation());
3210 QualType FType = Field->getType();
3211 uint64_t FieldSize = 0;
3212 uint32_t FieldAlign = 0;
3213
3214 if (!FType->isIncompleteArrayType()) {
3215
3216 // Bit size, align and offset of the type.
3217 FieldSize = Field->isBitField()
3218 ? Field->getBitWidthValue(CGM.getContext())
3219 : CGM.getContext().getTypeSize(FType);
3220 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3221 }
3222
3223 uint64_t FieldOffset;
3224 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3225 // We don't know the runtime offset of an ivar if we're using the
3226 // non-fragile ABI. For bitfields, use the bit offset into the first
3227 // byte of storage of the bitfield. For other fields, use zero.
3228 if (Field->isBitField()) {
3229 FieldOffset =
3230 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3231 FieldOffset %= CGM.getContext().getCharWidth();
3232 } else {
3233 FieldOffset = 0;
3234 }
3235 } else {
3236 FieldOffset = RL.getFieldOffset(FieldNo);
3237 }
3238
3239 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3240 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3241 Flags = llvm::DINode::FlagProtected;
3242 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3243 Flags = llvm::DINode::FlagPrivate;
3244 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3245 Flags = llvm::DINode::FlagPublic;
3246
3247 if (Field->isBitField())
3248 Flags |= llvm::DINode::FlagBitField;
3249
3250 llvm::MDNode *PropertyNode = nullptr;
3251 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3252 if (ObjCPropertyImplDecl *PImpD =
3253 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3254 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3255 SourceLocation Loc = PD->getLocation();
3256 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3257 unsigned PLine = getLineNumber(Loc);
3258 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3259 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3260 PropertyNode = DBuilder.createObjCProperty(
3261 PD->getName(), PUnit, PLine,
3262 hasDefaultGetterName(PD, Getter)
3263 ? ""
3264 : getSelectorName(PD->getGetterName()),
3265 hasDefaultSetterName(PD, Setter)
3266 ? ""
3267 : getSelectorName(PD->getSetterName()),
3268 PD->getPropertyAttributes(),
3269 getOrCreateType(PD->getType(), PUnit));
3270 }
3271 }
3272 }
3273 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3274 FieldSize, FieldAlign, FieldOffset, Flags,
3275 FieldTy, PropertyNode);
3276 EltTys.push_back(FieldTy);
3277 }
3278
3279 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3280 DBuilder.replaceArrays(RealDecl, Elements);
3281
3282 LexicalBlockStack.pop_back();
3283 return RealDecl;
3284}
3285
3286llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3287 llvm::DIFile *Unit) {
3288 if (Ty->isExtVectorBoolType()) {
3289 // Boolean ext_vector_type(N) are special because their real element type
3290 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3291 // For now, we pretend the boolean vector were actually a vector of bytes
3292 // (where each byte represents 8 bits of the actual vector).
3293 // FIXME Debug info should actually represent this proper as a vector mask
3294 // type.
3295 auto &Ctx = CGM.getContext();
3296 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3297 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3298
3299 // Construct the vector of 'char' type.
3300 QualType CharVecTy =
3301 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3302 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3303 }
3304
3305 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3306 int64_t Count = Ty->getNumElements();
3307
3308 llvm::Metadata *Subscript;
3309 QualType QTy(Ty, 0);
3310 auto SizeExpr = SizeExprCache.find(QTy);
3311 if (SizeExpr != SizeExprCache.end())
3312 Subscript = DBuilder.getOrCreateSubrange(
3313 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3314 nullptr /*upperBound*/, nullptr /*stride*/);
3315 else {
3316 auto *CountNode =
3317 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3318 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3319 Subscript = DBuilder.getOrCreateSubrange(
3320 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3321 nullptr /*stride*/);
3322 }
3323 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3324
3325 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3326 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3327
3328 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3329}
3330
3331llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3332 llvm::DIFile *Unit) {
3333 // FIXME: Create another debug type for matrices
3334 // For the time being, it treats it like a nested ArrayType.
3335
3336 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3337 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3338 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3339
3340 // Create ranges for both dimensions.
3342 auto *ColumnCountNode =
3343 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3344 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3345 auto *RowCountNode =
3346 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3347 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3348 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3349 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3350 nullptr /*stride*/));
3351 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3352 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3353 nullptr /*stride*/));
3354 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3355 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3356}
3357
3358llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3359 uint64_t Size;
3360 uint32_t Align;
3361
3362 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3363 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3364 Size = 0;
3366 CGM.getContext());
3367 } else if (Ty->isIncompleteArrayType()) {
3368 Size = 0;
3369 if (Ty->getElementType()->isIncompleteType())
3370 Align = 0;
3371 else
3372 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3373 } else if (Ty->isIncompleteType()) {
3374 Size = 0;
3375 Align = 0;
3376 } else {
3377 // Size and align of the whole array, not the element type.
3378 Size = CGM.getContext().getTypeSize(Ty);
3379 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3380 }
3381
3382 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3383 // interior arrays, do we care? Why aren't nested arrays represented the
3384 // obvious/recursive way?
3386 QualType EltTy(Ty, 0);
3387 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3388 // If the number of elements is known, then count is that number. Otherwise,
3389 // it's -1. This allows us to represent a subrange with an array of 0
3390 // elements, like this:
3391 //
3392 // struct foo {
3393 // int x[0];
3394 // };
3395 int64_t Count = -1; // Count == -1 is an unbounded array.
3396 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3397 Count = CAT->getZExtSize();
3398 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3399 if (Expr *Size = VAT->getSizeExpr()) {
3401 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3402 Count = Result.Val.getInt().getExtValue();
3403 }
3404 }
3405
3406 auto SizeNode = SizeExprCache.find(EltTy);
3407 if (SizeNode != SizeExprCache.end())
3408 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3409 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3410 nullptr /*upperBound*/, nullptr /*stride*/));
3411 else {
3412 auto *CountNode =
3413 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3414 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3415 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3416 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3417 nullptr /*stride*/));
3418 }
3419 EltTy = Ty->getElementType();
3420 }
3421
3422 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3423
3424 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3425 SubscriptArray);
3426}
3427
3428llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3429 llvm::DIFile *Unit) {
3430 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3431 Ty->getPointeeType(), Unit);
3432}
3433
3434llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3435 llvm::DIFile *Unit) {
3436 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3437 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3438 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3439 CGM.getCodeGenOpts().DwarfVersion < 4)
3440 Tag = llvm::dwarf::DW_TAG_reference_type;
3441
3442 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3443}
3444
3445llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3446 llvm::DIFile *U) {
3447 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3448 uint64_t Size = 0;
3449
3450 if (!Ty->isIncompleteType()) {
3451 Size = CGM.getContext().getTypeSize(Ty);
3452
3453 // Set the MS inheritance model. There is no flag for the unspecified model.
3454 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3457 Flags |= llvm::DINode::FlagSingleInheritance;
3458 break;
3460 Flags |= llvm::DINode::FlagMultipleInheritance;
3461 break;
3463 Flags |= llvm::DINode::FlagVirtualInheritance;
3464 break;
3466 break;
3467 }
3468 }
3469 }
3470
3471 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3472 if (Ty->isMemberDataPointerType())
3473 return DBuilder.createMemberPointerType(
3474 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3475 Flags);
3476
3477 const FunctionProtoType *FPT =
3479 return DBuilder.createMemberPointerType(
3480 getOrCreateInstanceMethodType(
3482 FPT, U),
3483 ClassType, Size, /*Align=*/0, Flags);
3484}
3485
3486llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3487 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3488 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3489}
3490
3491llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3492 return getOrCreateType(Ty->getElementType(), U);
3493}
3494
3495llvm::DIType *CGDebugInfo::CreateType(const HLSLAttributedResourceType *Ty,
3496 llvm::DIFile *U) {
3497 return getOrCreateType(Ty->getWrappedType(), U);
3498}
3499
3500llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3501 const EnumDecl *ED = Ty->getDecl();
3502
3503 uint64_t Size = 0;
3504 uint32_t Align = 0;
3505 if (!ED->getTypeForDecl()->isIncompleteType()) {
3507 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3508 }
3509
3511
3512 bool isImportedFromModule =
3513 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3514
3515 // If this is just a forward declaration, construct an appropriately
3516 // marked node and just return it.
3517 if (isImportedFromModule || !ED->getDefinition()) {
3518 // Note that it is possible for enums to be created as part of
3519 // their own declcontext. In this case a FwdDecl will be created
3520 // twice. This doesn't cause a problem because both FwdDecls are
3521 // entered into the ReplaceMap: finalize() will replace the first
3522 // FwdDecl with the second and then replace the second with
3523 // complete type.
3524 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3525 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3526 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3527 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3528
3529 unsigned Line = getLineNumber(ED->getLocation());
3530 StringRef EDName = ED->getName();
3531 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3532 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3533 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3534
3535 ReplaceMap.emplace_back(
3536 std::piecewise_construct, std::make_tuple(Ty),
3537 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3538 return RetTy;
3539 }
3540
3541 return CreateTypeDefinition(Ty);
3542}
3543
3544llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3545 const EnumDecl *ED = Ty->getDecl();
3546 uint64_t Size = 0;
3547 uint32_t Align = 0;
3548 if (!ED->getTypeForDecl()->isIncompleteType()) {
3550 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3551 }
3552
3554
3556 ED = ED->getDefinition();
3557 assert(ED && "An enumeration definition is required");
3558 for (const auto *Enum : ED->enumerators()) {
3559 Enumerators.push_back(
3560 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3561 }
3562
3563 // Return a CompositeType for the enum itself.
3564 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3565
3566 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3567 unsigned Line = getLineNumber(ED->getLocation());
3568 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3569 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3570 return DBuilder.createEnumerationType(
3571 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3572 /*RunTimeLang=*/0, Identifier, ED->isScoped());
3573}
3574
3575llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3576 unsigned MType, SourceLocation LineLoc,
3577 StringRef Name, StringRef Value) {
3578 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3579 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3580}
3581
3582llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3583 SourceLocation LineLoc,
3584 SourceLocation FileLoc) {
3585 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3586 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3587 return DBuilder.createTempMacroFile(Parent, Line, FName);
3588}
3589
3591 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
3592 // Create a debug location from `TrapLocation` that adds an artificial inline
3593 // frame.
3595
3596 FuncName += "$";
3597 FuncName += Category;
3598 FuncName += "$";
3599 FuncName += FailureMsg;
3600
3601 llvm::DISubprogram *TrapSP =
3602 createInlinedTrapSubprogram(FuncName, TrapLocation->getFile());
3603 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
3604 /*Scope=*/TrapSP, /*InlinedAt=*/TrapLocation);
3605}
3606
3608 Qualifiers Quals;
3609 do {
3610 Qualifiers InnerQuals = T.getLocalQualifiers();
3611 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3612 // that is already there.
3613 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3614 Quals += InnerQuals;
3615 QualType LastT = T;
3616 switch (T->getTypeClass()) {
3617 default:
3618 return C.getQualifiedType(T.getTypePtr(), Quals);
3619 case Type::TemplateSpecialization: {
3620 const auto *Spec = cast<TemplateSpecializationType>(T);
3621 if (Spec->isTypeAlias())
3622 return C.getQualifiedType(T.getTypePtr(), Quals);
3623 T = Spec->desugar();
3624 break;
3625 }
3626 case Type::TypeOfExpr:
3627 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3628 break;
3629 case Type::TypeOf:
3630 T = cast<TypeOfType>(T)->getUnmodifiedType();
3631 break;
3632 case Type::Decltype:
3633 T = cast<DecltypeType>(T)->getUnderlyingType();
3634 break;
3635 case Type::UnaryTransform:
3636 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3637 break;
3638 case Type::Attributed:
3639 T = cast<AttributedType>(T)->getEquivalentType();
3640 break;
3641 case Type::BTFTagAttributed:
3642 T = cast<BTFTagAttributedType>(T)->getWrappedType();
3643 break;
3644 case Type::CountAttributed:
3645 T = cast<CountAttributedType>(T)->desugar();
3646 break;
3647 case Type::Elaborated:
3648 T = cast<ElaboratedType>(T)->getNamedType();
3649 break;
3650 case Type::Using:
3651 T = cast<UsingType>(T)->getUnderlyingType();
3652 break;
3653 case Type::Paren:
3654 T = cast<ParenType>(T)->getInnerType();
3655 break;
3656 case Type::MacroQualified:
3657 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3658 break;
3659 case Type::SubstTemplateTypeParm:
3660 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3661 break;
3662 case Type::Auto:
3663 case Type::DeducedTemplateSpecialization: {
3664 QualType DT = cast<DeducedType>(T)->getDeducedType();
3665 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3666 T = DT;
3667 break;
3668 }
3669 case Type::PackIndexing: {
3670 T = cast<PackIndexingType>(T)->getSelectedType();
3671 break;
3672 }
3673 case Type::Adjusted:
3674 case Type::Decayed:
3675 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3676 T = cast<AdjustedType>(T)->getAdjustedType();
3677 break;
3678 }
3679
3680 assert(T != LastT && "Type unwrapping failed to unwrap!");
3681 (void)LastT;
3682 } while (true);
3683}
3684
3685llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3686 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3687 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3688 if (It != TypeCache.end()) {
3689 // Verify that the debug info still exists.
3690 if (llvm::Metadata *V = It->second)
3691 return cast<llvm::DIType>(V);
3692 }
3693
3694 return nullptr;
3695}
3696
3700}
3701
3703 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
3704 D.isDynamicClass())
3705 return;
3706
3708 // In case this type has no member function definitions being emitted, ensure
3709 // it is retained
3710 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3711}
3712
3713llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3714 if (Ty.isNull())
3715 return nullptr;
3716
3717 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3718 std::string Name;
3719 llvm::raw_string_ostream OS(Name);
3720 Ty.print(OS, getPrintingPolicy());
3721 return Name;
3722 });
3723
3724 // Unwrap the type as needed for debug information.
3725 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3726
3727 if (auto *T = getTypeOrNull(Ty))
3728 return T;
3729
3730 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3731 void *TyPtr = Ty.getAsOpaquePtr();
3732
3733 // And update the type cache.
3734 TypeCache[TyPtr].reset(Res);
3735
3736 return Res;
3737}
3738
3739llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3740 // A forward declaration inside a module header does not belong to the module.
3741 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3742 return nullptr;
3743 if (DebugTypeExtRefs && D->isFromASTFile()) {
3744 // Record a reference to an imported clang module or precompiled header.
3745 auto *Reader = CGM.getContext().getExternalSource();
3746 auto Idx = D->getOwningModuleID();
3747 auto Info = Reader->getSourceDescriptor(Idx);
3748 if (Info)
3749 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3750 } else if (ClangModuleMap) {
3751 // We are building a clang module or a precompiled header.
3752 //
3753 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3754 // and it wouldn't be necessary to specify the parent scope
3755 // because the type is already unique by definition (it would look
3756 // like the output of -fno-standalone-debug). On the other hand,
3757 // the parent scope helps a consumer to quickly locate the object
3758 // file where the type's definition is located, so it might be
3759 // best to make this behavior a command line or debugger tuning
3760 // option.
3761 if (Module *M = D->getOwningModule()) {
3762 // This is a (sub-)module.
3763 auto Info = ASTSourceDescriptor(*M);
3764 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3765 } else {
3766 // This the precompiled header being built.
3767 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3768 }
3769 }
3770
3771 return nullptr;
3772}
3773
3774llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3775 // Handle qualifiers, which recursively handles what they refer to.
3776 if (Ty.hasLocalQualifiers())
3777 return CreateQualifiedType(Ty, Unit);
3778
3779 // Work out details of type.
3780 switch (Ty->getTypeClass()) {
3781#define TYPE(Class, Base)
3782#define ABSTRACT_TYPE(Class, Base)
3783#define NON_CANONICAL_TYPE(Class, Base)
3784#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3785#include "clang/AST/TypeNodes.inc"
3786 llvm_unreachable("Dependent types cannot show up in debug information");
3787
3788 case Type::ExtVector:
3789 case Type::Vector:
3790 return CreateType(cast<VectorType>(Ty), Unit);
3791 case Type::ConstantMatrix:
3792 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3793 case Type::ObjCObjectPointer:
3794 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3795 case Type::ObjCObject:
3796 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3797 case Type::ObjCTypeParam:
3798 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3799 case Type::ObjCInterface:
3800 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3801 case Type::Builtin:
3802 return CreateType(cast<BuiltinType>(Ty));
3803 case Type::Complex:
3804 return CreateType(cast<ComplexType>(Ty));
3805 case Type::Pointer:
3806 return CreateType(cast<PointerType>(Ty), Unit);
3807 case Type::BlockPointer:
3808 return CreateType(cast<BlockPointerType>(Ty), Unit);
3809 case Type::Typedef:
3810 return CreateType(cast<TypedefType>(Ty), Unit);
3811 case Type::Record:
3812 return CreateType(cast<RecordType>(Ty));
3813 case Type::Enum:
3814 return CreateEnumType(cast<EnumType>(Ty));
3815 case Type::FunctionProto:
3816 case Type::FunctionNoProto:
3817 return CreateType(cast<FunctionType>(Ty), Unit);
3818 case Type::ConstantArray:
3819 case Type::VariableArray:
3820 case Type::IncompleteArray:
3821 case Type::ArrayParameter:
3822 return CreateType(cast<ArrayType>(Ty), Unit);
3823
3824 case Type::LValueReference:
3825 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3826 case Type::RValueReference:
3827 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3828
3829 case Type::MemberPointer:
3830 return CreateType(cast<MemberPointerType>(Ty), Unit);
3831
3832 case Type::Atomic:
3833 return CreateType(cast<AtomicType>(Ty), Unit);
3834
3835 case Type::BitInt:
3836 return CreateType(cast<BitIntType>(Ty));
3837 case Type::Pipe:
3838 return CreateType(cast<PipeType>(Ty), Unit);
3839
3840 case Type::TemplateSpecialization:
3841 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3842 case Type::HLSLAttributedResource:
3843 return CreateType(cast<HLSLAttributedResourceType>(Ty), Unit);
3844
3845 case Type::CountAttributed:
3846 case Type::Auto:
3847 case Type::Attributed:
3848 case Type::BTFTagAttributed:
3849 case Type::Adjusted:
3850 case Type::Decayed:
3851 case Type::DeducedTemplateSpecialization:
3852 case Type::Elaborated:
3853 case Type::Using:
3854 case Type::Paren:
3855 case Type::MacroQualified:
3856 case Type::SubstTemplateTypeParm:
3857 case Type::TypeOfExpr:
3858 case Type::TypeOf:
3859 case Type::Decltype:
3860 case Type::PackIndexing:
3861 case Type::UnaryTransform:
3862 break;
3863 }
3864
3865 llvm_unreachable("type should have been unwrapped!");
3866}
3867
3868llvm::DICompositeType *
3869CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3870 QualType QTy(Ty, 0);
3871
3872 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3873
3874 // We may have cached a forward decl when we could have created
3875 // a non-forward decl. Go ahead and create a non-forward decl
3876 // now.
3877 if (T && !T->isForwardDecl())
3878 return T;
3879
3880 // Otherwise create the type.
3881 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3882
3883 // Propagate members from the declaration to the definition
3884 // CreateType(const RecordType*) will overwrite this with the members in the
3885 // correct order if the full type is needed.
3886 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3887
3888 // And update the type cache.
3889 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3890 return Res;
3891}
3892
3893// TODO: Currently used for context chains when limiting debug info.
3894llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3895 RecordDecl *RD = Ty->getDecl();
3896
3897 // Get overall information about the record type for the debug info.
3898 StringRef RDName = getClassName(RD);
3899 const SourceLocation Loc = RD->getLocation();
3900 llvm::DIFile *DefUnit = nullptr;
3901 unsigned Line = 0;
3902 if (Loc.isValid()) {
3903 DefUnit = getOrCreateFile(Loc);
3904 Line = getLineNumber(Loc);
3905 }
3906
3907 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3908
3909 // If we ended up creating the type during the context chain construction,
3910 // just return that.
3911 auto *T = cast_or_null<llvm::DICompositeType>(
3912 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3913 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3914 return T;
3915
3916 // If this is just a forward or incomplete declaration, construct an
3917 // appropriately marked node and just return it.
3918 const RecordDecl *D = RD->getDefinition();
3919 if (!D || !D->isCompleteDefinition())
3920 return getOrCreateRecordFwdDecl(Ty, RDContext);
3921
3922 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3923 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3924 // struct or struct member, where it only increases alignment unless 'packed'
3925 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3926 // to be used.
3927 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3928
3930
3931 // Explicitly record the calling convention and export symbols for C++
3932 // records.
3933 auto Flags = llvm::DINode::FlagZero;
3934 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3936 Flags |= llvm::DINode::FlagTypePassByReference;
3937 else
3938 Flags |= llvm::DINode::FlagTypePassByValue;
3939
3940 // Record if a C++ record is non-trivial type.
3941 if (!CXXRD->isTrivial())
3942 Flags |= llvm::DINode::FlagNonTrivial;
3943
3944 // Record exports it symbols to the containing structure.
3945 if (CXXRD->isAnonymousStructOrUnion())
3946 Flags |= llvm::DINode::FlagExportSymbols;
3947
3948 Flags |= getAccessFlag(CXXRD->getAccess(),
3949 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3950 }
3951
3952 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3953 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3954 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3955 Flags, Identifier, Annotations);
3956
3957 // Elements of composite types usually have back to the type, creating
3958 // uniquing cycles. Distinct nodes are more efficient.
3959 switch (RealDecl->getTag()) {
3960 default:
3961 llvm_unreachable("invalid composite type tag");
3962
3963 case llvm::dwarf::DW_TAG_array_type:
3964 case llvm::dwarf::DW_TAG_enumeration_type:
3965 // Array elements and most enumeration elements don't have back references,
3966 // so they don't tend to be involved in uniquing cycles and there is some
3967 // chance of merging them when linking together two modules. Only make
3968 // them distinct if they are ODR-uniqued.
3969 if (Identifier.empty())
3970 break;
3971 [[fallthrough]];
3972
3973 case llvm::dwarf::DW_TAG_structure_type:
3974 case llvm::dwarf::DW_TAG_union_type:
3975 case llvm::dwarf::DW_TAG_class_type:
3976 // Immediately resolve to a distinct node.
3977 RealDecl =
3978 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3979 break;
3980 }
3981
3982 RegionMap[Ty->getDecl()].reset(RealDecl);
3983 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3984
3985 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3986 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3987 CollectCXXTemplateParams(TSpecial, DefUnit));
3988 return RealDecl;
3989}
3990
3991void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3992 llvm::DICompositeType *RealDecl) {
3993 // A class's primary base or the class itself contains the vtable.
3994 llvm::DIType *ContainingType = nullptr;
3995 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3996 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3997 // Seek non-virtual primary base root.
3998 while (true) {
3999 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
4000 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
4001 if (PBT && !BRL.isPrimaryBaseVirtual())
4002 PBase = PBT;
4003 else
4004 break;
4005 }
4006 ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
4007 getOrCreateFile(RD->getLocation()));
4008 } else if (RD->isDynamicClass())
4009 ContainingType = RealDecl;
4010
4011 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4012}
4013
4014llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4015 StringRef Name, uint64_t *Offset) {
4016 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4017 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4018 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4019 llvm::DIType *Ty =
4020 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4021 *Offset, llvm::DINode::FlagZero, FieldTy);
4022 *Offset += FieldSize;
4023 return Ty;
4024}
4025
4026void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4027 StringRef &Name,
4028 StringRef &LinkageName,
4029 llvm::DIScope *&FDContext,
4030 llvm::DINodeArray &TParamsArray,
4031 llvm::DINode::DIFlags &Flags) {
4032 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4033 Name = getFunctionName(FD);
4034 // Use mangled name as linkage name for C/C++ functions.
4035 if (FD->getType()->getAs<FunctionProtoType>())
4036 LinkageName = CGM.getMangledName(GD);
4037 if (FD->hasPrototype())
4038 Flags |= llvm::DINode::FlagPrototyped;
4039 // No need to replicate the linkage name if it isn't different from the
4040 // subprogram name, no need to have it at all unless coverage is enabled or
4041 // debug is set to more than just line tables or extra debug info is needed.
4042 if (LinkageName == Name ||
4043 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4044 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4045 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4046 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4047 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4048 LinkageName = StringRef();
4049
4050 // Emit the function scope in line tables only mode (if CodeView) to
4051 // differentiate between function names.
4052 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4053 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4054 CGM.getCodeGenOpts().EmitCodeView)) {
4055 if (const NamespaceDecl *NSDecl =
4056 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4057 FDContext = getOrCreateNamespace(NSDecl);
4058 else if (const RecordDecl *RDecl =
4059 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4060 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4061 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4062 }
4063 }
4064 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4065 // Check if it is a noreturn-marked function
4066 if (FD->isNoReturn())
4067 Flags |= llvm::DINode::FlagNoReturn;
4068 // Collect template parameters.
4069 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4070 }
4071}
4072
4073void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4074 unsigned &LineNo, QualType &T,
4075 StringRef &Name, StringRef &LinkageName,
4076 llvm::MDTuple *&TemplateParameters,
4077 llvm::DIScope *&VDContext) {
4078 Unit = getOrCreateFile(VD->getLocation());
4079 LineNo = getLineNumber(VD->getLocation());
4080
4081 setLocation(VD->getLocation());
4082
4083 T = VD->getType();
4084 if (T->isIncompleteArrayType()) {
4085 // CodeGen turns int[] into int[1] so we'll do the same here.
4086 llvm::APInt ConstVal(32, 1);
4088
4089 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4091 }
4092
4093 Name = VD->getName();
4094 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4095 !isa<ObjCMethodDecl>(VD->getDeclContext()))
4096 LinkageName = CGM.getMangledName(VD);
4097 if (LinkageName == Name)
4098 LinkageName = StringRef();
4099
4100 if (isa<VarTemplateSpecializationDecl>(VD)) {
4101 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4102 TemplateParameters = parameterNodes.get();
4103 } else {
4104 TemplateParameters = nullptr;
4105 }
4106
4107 // Since we emit declarations (DW_AT_members) for static members, place the
4108 // definition of those static members in the namespace they were declared in
4109 // in the source code (the lexical decl context).
4110 // FIXME: Generalize this for even non-member global variables where the
4111 // declaration and definition may have different lexical decl contexts, once
4112 // we have support for emitting declarations of (non-member) global variables.
4113 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4114 : VD->getDeclContext();
4115 // When a record type contains an in-line initialization of a static data
4116 // member, and the record type is marked as __declspec(dllexport), an implicit
4117 // definition of the member will be created in the record context. DWARF
4118 // doesn't seem to have a nice way to describe this in a form that consumers
4119 // are likely to understand, so fake the "normal" situation of a definition
4120 // outside the class by putting it in the global scope.
4121 if (DC->isRecord())
4123
4124 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4125 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4126}
4127
4128llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4129 bool Stub) {
4130 llvm::DINodeArray TParamsArray;
4131 StringRef Name, LinkageName;
4132 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4133 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4135 llvm::DIFile *Unit = getOrCreateFile(Loc);
4136 llvm::DIScope *DContext = Unit;
4137 unsigned Line = getLineNumber(Loc);
4138 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4139 Flags);
4140 auto *FD = cast<FunctionDecl>(GD.getDecl());
4141
4142 // Build function type.
4144 for (const ParmVarDecl *Parm : FD->parameters())
4145 ArgTypes.push_back(Parm->getType());
4146
4147 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4148 QualType FnType = CGM.getContext().getFunctionType(
4149 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4150 if (!FD->isExternallyVisible())
4151 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4152 if (CGM.getLangOpts().Optimize)
4153 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4154
4155 if (Stub) {
4156 Flags |= getCallSiteRelatedAttrs();
4157 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4158 return DBuilder.createFunction(
4159 DContext, Name, LinkageName, Unit, Line,
4160 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4161 TParamsArray.get(), getFunctionDeclaration(FD));
4162 }
4163
4164 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4165 DContext, Name, LinkageName, Unit, Line,
4166 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4167 TParamsArray.get(), getFunctionDeclaration(FD));
4168 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4169 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4170 std::make_tuple(CanonDecl),
4171 std::make_tuple(SP));
4172 return SP;
4173}
4174
4175llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4176 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4177}
4178
4179llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4180 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4181}
4182
4183llvm::DIGlobalVariable *
4184CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4185 QualType T;
4186 StringRef Name, LinkageName;
4188 llvm::DIFile *Unit = getOrCreateFile(Loc);
4189 llvm::DIScope *DContext = Unit;
4190 unsigned Line = getLineNumber(Loc);
4191 llvm::MDTuple *TemplateParameters = nullptr;
4192
4193 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4194 DContext);
4195 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4196 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4197 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4198 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4199 FwdDeclReplaceMap.emplace_back(
4200 std::piecewise_construct,
4201 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4202 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4203 return GV;
4204}
4205
4206llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4207 // We only need a declaration (not a definition) of the type - so use whatever
4208 // we would otherwise do to get a type for a pointee. (forward declarations in
4209 // limited debug info, full definitions (if the type definition is available)
4210 // in unlimited debug info)
4211 if (const auto *TD = dyn_cast<TypeDecl>(D))
4212 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
4213 getOrCreateFile(TD->getLocation()));
4214 auto I = DeclCache.find(D->getCanonicalDecl());
4215
4216 if (I != DeclCache.end()) {
4217 auto N = I->second;
4218 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4219 return GVE->getVariable();
4220 return cast<llvm::DINode>(N);
4221 }
4222
4223 // Search imported declaration cache if it is already defined
4224 // as imported declaration.
4225 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4226
4227 if (IE != ImportedDeclCache.end()) {
4228 auto N = IE->second;
4229 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4230 return cast<llvm::DINode>(GVE);
4231 return dyn_cast_or_null<llvm::DINode>(N);
4232 }
4233
4234 // No definition for now. Emit a forward definition that might be
4235 // merged with a potential upcoming definition.
4236 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4237 return getFunctionForwardDeclaration(FD);
4238 else if (const auto *VD = dyn_cast<VarDecl>(D))
4239 return getGlobalVariableForwardDeclaration(VD);
4240
4241 return nullptr;
4242}
4243
4244llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4245 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4246 return nullptr;
4247
4248 const auto *FD = dyn_cast<FunctionDecl>(D);
4249 if (!FD)
4250 return nullptr;
4251
4252 // Setup context.
4253 auto *S = getDeclContextDescriptor(D);
4254
4255 auto MI = SPCache.find(FD->getCanonicalDecl());
4256 if (MI == SPCache.end()) {
4257 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4258 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4259 cast<llvm::DICompositeType>(S));
4260 }
4261 }
4262 if (MI != SPCache.end()) {
4263 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4264 if (SP && !SP->isDefinition())
4265 return SP;
4266 }
4267
4268 for (auto *NextFD : FD->redecls()) {
4269 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4270 if (MI != SPCache.end()) {
4271 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4272 if (SP && !SP->isDefinition())
4273 return SP;
4274 }
4275 }
4276 return nullptr;
4277}
4278
4279llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4280 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4281 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4282 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4283 return nullptr;
4284
4285 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4286 if (!OMD)
4287 return nullptr;
4288
4289 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4290 return nullptr;
4291
4292 if (OMD->isDirectMethod())
4293 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4294
4295 // Starting with DWARF V5 method declarations are emitted as children of
4296 // the interface type.
4297 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4298 if (!ID)
4299 ID = OMD->getClassInterface();
4300 if (!ID)
4301 return nullptr;
4302 QualType QTy(ID->getTypeForDecl(), 0);
4303 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4304 if (It == TypeCache.end())
4305 return nullptr;
4306 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4307 llvm::DISubprogram *FD = DBuilder.createFunction(
4308 InterfaceType, getObjCMethodName(OMD), StringRef(),
4309 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4310 DBuilder.finalizeSubprogram(FD);
4311 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4312 return FD;
4313}
4314
4315// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4316// implicit parameter "this".
4317llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4318 QualType FnType,
4319 llvm::DIFile *F) {
4320 // In CodeView, we emit the function types in line tables only because the
4321 // only way to distinguish between functions is by display name and type.
4322 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4323 !CGM.getCodeGenOpts().EmitCodeView))
4324 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4325 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4326 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4327
4328 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4329 return getOrCreateMethodType(Method, F);
4330
4331 const auto *FTy = FnType->getAs<FunctionType>();
4332 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4333
4334 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4335 // Add "self" and "_cmd"
4337
4338 // First element is always return type. For 'void' functions it is NULL.
4339 QualType ResultTy = OMethod->getReturnType();
4340
4341 // Replace the instancetype keyword with the actual type.
4342 if (ResultTy == CGM.getContext().getObjCInstanceType())
4343 ResultTy = CGM.getContext().getPointerType(
4344 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4345
4346 Elts.push_back(getOrCreateType(ResultTy, F));
4347 // "self" pointer is always first argument.
4348 QualType SelfDeclTy;
4349 if (auto *SelfDecl = OMethod->getSelfDecl())
4350 SelfDeclTy = SelfDecl->getType();
4351 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4352 if (FPT->getNumParams() > 1)
4353 SelfDeclTy = FPT->getParamType(0);
4354 if (!SelfDeclTy.isNull())
4355 Elts.push_back(
4356 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4357 // "_cmd" pointer is always second argument.
4358 Elts.push_back(DBuilder.createArtificialType(
4359 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4360 // Get rest of the arguments.
4361 for (const auto *PI : OMethod->parameters())
4362 Elts.push_back(getOrCreateType(PI->getType(), F));
4363 // Variadic methods need a special marker at the end of the type list.
4364 if (OMethod->isVariadic())
4365 Elts.push_back(DBuilder.createUnspecifiedParameter());
4366
4367 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4368 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4369 getDwarfCC(CC));
4370 }
4371
4372 // Handle variadic function types; they need an additional
4373 // unspecified parameter.
4374 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4375 if (FD->isVariadic()) {
4377 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4378 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4379 for (QualType ParamType : FPT->param_types())
4380 EltTys.push_back(getOrCreateType(ParamType, F));
4381 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4382 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4383 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4384 getDwarfCC(CC));
4385 }
4386
4387 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4388}
4389
4394 if (FD)
4395 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4396 CC = SrcFnTy->getCallConv();
4398 for (const VarDecl *VD : Args)
4399 ArgTypes.push_back(VD->getType());
4400 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4402}
4403
4405 SourceLocation ScopeLoc, QualType FnType,
4406 llvm::Function *Fn, bool CurFuncIsThunk) {
4407 StringRef Name;
4408 StringRef LinkageName;
4409
4410 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4411
4412 const Decl *D = GD.getDecl();
4413 bool HasDecl = (D != nullptr);
4414
4415 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4416 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4417 llvm::DIFile *Unit = getOrCreateFile(Loc);
4418 llvm::DIScope *FDContext = Unit;
4419 llvm::DINodeArray TParamsArray;
4420 if (!HasDecl) {
4421 // Use llvm function name.
4422 LinkageName = Fn->getName();
4423 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4424 // If there is a subprogram for this function available then use it.
4425 auto FI = SPCache.find(FD->getCanonicalDecl());
4426 if (FI != SPCache.end()) {
4427 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4428 if (SP && SP->isDefinition()) {
4429 LexicalBlockStack.emplace_back(SP);
4430 RegionMap[D].reset(SP);
4431 return;
4432 }
4433 }
4434 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4435 TParamsArray, Flags);
4436 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4437 Name = getObjCMethodName(OMD);
4438 Flags |= llvm::DINode::FlagPrototyped;
4439 } else if (isa<VarDecl>(D) &&
4441 // This is a global initializer or atexit destructor for a global variable.
4442 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4443 Fn);
4444 } else {
4445 Name = Fn->getName();
4446
4447 if (isa<BlockDecl>(D))
4448 LinkageName = Name;
4449
4450 Flags |= llvm::DINode::FlagPrototyped;
4451 }
4452 if (Name.starts_with("\01"))
4453 Name = Name.substr(1);
4454
4455 assert((!D || !isa<VarDecl>(D) ||
4457 "Unexpected DynamicInitKind !");
4458
4459 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4460 isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4461 Flags |= llvm::DINode::FlagArtificial;
4462 // Artificial functions should not silently reuse CurLoc.
4463 CurLoc = SourceLocation();
4464 }
4465
4466 if (CurFuncIsThunk)
4467 Flags |= llvm::DINode::FlagThunk;
4468
4469 if (Fn->hasLocalLinkage())
4470 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4471 if (CGM.getLangOpts().Optimize)
4472 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4473
4474 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4475 llvm::DISubprogram::DISPFlags SPFlagsForDef =
4476 SPFlags | llvm::DISubprogram::SPFlagDefinition;
4477
4478 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4479 unsigned ScopeLine = getLineNumber(ScopeLoc);
4480 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4481 llvm::DISubprogram *Decl = nullptr;
4482 llvm::DINodeArray Annotations = nullptr;
4483 if (D) {
4484 Decl = isa<ObjCMethodDecl>(D)
4485 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4486 : getFunctionDeclaration(D);
4487 Annotations = CollectBTFDeclTagAnnotations(D);
4488 }
4489
4490 // FIXME: The function declaration we're constructing here is mostly reusing
4491 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4492 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4493 // all subprograms instead of the actual context since subprogram definitions
4494 // are emitted as CU level entities by the backend.
4495 llvm::DISubprogram *SP = DBuilder.createFunction(
4496 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4497 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4498 Annotations);
4499 Fn->setSubprogram(SP);
4500 // We might get here with a VarDecl in the case we're generating
4501 // code for the initialization of globals. Do not record these decls
4502 // as they will overwrite the actual VarDecl Decl in the cache.
4503 if (HasDecl && isa<FunctionDecl>(D))
4504 DeclCache[D->getCanonicalDecl()].reset(SP);
4505
4506 // Push the function onto the lexical block stack.
4507 LexicalBlockStack.emplace_back(SP);
4508
4509 if (HasDecl)
4510 RegionMap[D].reset(SP);
4511}
4512
4514 QualType FnType, llvm::Function *Fn) {
4515 StringRef Name;
4516 StringRef LinkageName;
4517
4518 const Decl *D = GD.getDecl();
4519 if (!D)
4520 return;
4521
4522 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4523 return GetName(D, true);
4524 });
4525
4526 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4527 llvm::DIFile *Unit = getOrCreateFile(Loc);
4528 bool IsDeclForCallSite = Fn ? true : false;
4529 llvm::DIScope *FDContext =
4530 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4531 llvm::DINodeArray TParamsArray;
4532 if (isa<FunctionDecl>(D)) {
4533 // If there is a DISubprogram for this function available then use it.
4534 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4535 TParamsArray, Flags);
4536 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4537 Name = getObjCMethodName(OMD);
4538 Flags |= llvm::DINode::FlagPrototyped;
4539 } else {
4540 llvm_unreachable("not a function or ObjC method");
4541 }
4542 if (!Name.empty() && Name[0] == '\01')
4543 Name = Name.substr(1);
4544
4545 if (D->isImplicit()) {
4546 Flags |= llvm::DINode::FlagArtificial;
4547 // Artificial functions without a location should not silently reuse CurLoc.
4548 if (Loc.isInvalid())
4549 CurLoc = SourceLocation();
4550 }
4551 unsigned LineNo = getLineNumber(Loc);
4552 unsigned ScopeLine = 0;
4553 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4554 if (CGM.getLangOpts().Optimize)
4555 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4556
4557 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4558 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4559 llvm::DISubprogram *SP = DBuilder.createFunction(
4560 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4561 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
4562
4563 // Preserve btf_decl_tag attributes for parameters of extern functions
4564 // for BPF target. The parameters created in this loop are attached as
4565 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4566 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4567 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4568 llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4569 unsigned ArgNo = 1;
4570 for (ParmVarDecl *PD : FD->parameters()) {
4571 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4572 DBuilder.createParameterVariable(
4573 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4574 llvm::DINode::FlagZero, ParamAnnotations);
4575 ++ArgNo;
4576 }
4577 }
4578 }
4579
4580 if (IsDeclForCallSite)
4581 Fn->setSubprogram(SP);
4582
4583 DBuilder.finalizeSubprogram(SP);
4584}
4585
4586void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4587 QualType CalleeType,
4588 const FunctionDecl *CalleeDecl) {
4589 if (!CallOrInvoke)
4590 return;
4591 auto *Func = CallOrInvoke->getCalledFunction();
4592 if (!Func)
4593 return;
4594 if (Func->getSubprogram())
4595 return;
4596
4597 // Do not emit a declaration subprogram for a function with nodebug
4598 // attribute, or if call site info isn't required.
4599 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4600 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4601 return;
4602
4603 // If there is no DISubprogram attached to the function being called,
4604 // create the one describing the function in order to have complete
4605 // call site debug info.
4606 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4607 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4608}
4609
4611 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4612 // If there is a subprogram for this function available then use it.
4613 auto FI = SPCache.find(FD->getCanonicalDecl());
4614 llvm::DISubprogram *SP = nullptr;
4615 if (FI != SPCache.end())
4616 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4617 if (!SP || !SP->isDefinition())
4618 SP = getFunctionStub(GD);
4619 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4620 LexicalBlockStack.emplace_back(SP);
4621 setInlinedAt(Builder.getCurrentDebugLocation());
4622 EmitLocation(Builder, FD->getLocation());
4623}
4624
4626 assert(CurInlinedAt && "unbalanced inline scope stack");
4627 EmitFunctionEnd(Builder, nullptr);
4628 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4629}
4630
4632 // Update our current location
4634
4635 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4636 return;
4637
4638 llvm::MDNode *Scope = LexicalBlockStack.back();
4639 Builder.SetCurrentDebugLocation(
4640 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4641 getColumnNumber(CurLoc), Scope, CurInlinedAt));
4642}
4643
4644void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4645 llvm::MDNode *Back = nullptr;
4646 if (!LexicalBlockStack.empty())
4647 Back = LexicalBlockStack.back().get();
4648 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4649 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4650 getColumnNumber(CurLoc)));
4651}
4652
4653void CGDebugInfo::AppendAddressSpaceXDeref(
4654 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4655 std::optional<unsigned> DWARFAddressSpace =
4656 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4657 if (!DWARFAddressSpace)
4658 return;
4659
4660 Expr.push_back(llvm::dwarf::DW_OP_constu);
4661 Expr.push_back(*DWARFAddressSpace);
4662 Expr.push_back(llvm::dwarf::DW_OP_swap);
4663 Expr.push_back(llvm::dwarf::DW_OP_xderef);
4664}
4665
4668 // Set our current location.
4670
4671 // Emit a line table change for the current location inside the new scope.
4672 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4673 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4674 LexicalBlockStack.back(), CurInlinedAt));
4675
4676 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4677 return;
4678
4679 // Create a new lexical block and push it on the stack.
4680 CreateLexicalBlock(Loc);
4681}
4682
4685 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4686
4687 // Provide an entry in the line table for the end of the block.
4688 EmitLocation(Builder, Loc);
4689
4690 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4691 return;
4692
4693 LexicalBlockStack.pop_back();
4694}
4695
4696void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4697 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4698 unsigned RCount = FnBeginRegionCount.back();
4699 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4700
4701 // Pop all regions for this function.
4702 while (LexicalBlockStack.size() != RCount) {
4703 // Provide an entry in the line table for the end of the block.
4704 EmitLocation(Builder, CurLoc);
4705 LexicalBlockStack.pop_back();
4706 }
4707 FnBeginRegionCount.pop_back();
4708
4709 if (Fn && Fn->getSubprogram())
4710 DBuilder.finalizeSubprogram(Fn->getSubprogram());
4711}
4712
4713CGDebugInfo::BlockByRefType
4714CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4715 uint64_t *XOffset) {
4717 QualType FType;
4718 uint64_t FieldSize, FieldOffset;
4719 uint32_t FieldAlign;
4720
4721 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4722 QualType Type = VD->getType();
4723
4724 FieldOffset = 0;
4725 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4726 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4727 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4728 FType = CGM.getContext().IntTy;
4729 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4730 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4731
4732 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4733 if (HasCopyAndDispose) {
4734 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4735 EltTys.push_back(
4736 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4737 EltTys.push_back(
4738 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4739 }
4740 bool HasByrefExtendedLayout;
4741 Qualifiers::ObjCLifetime Lifetime;
4742 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4743 HasByrefExtendedLayout) &&
4744 HasByrefExtendedLayout) {
4745 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4746 EltTys.push_back(
4747 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4748 }
4749
4750 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4751 if (Align > CGM.getContext().toCharUnitsFromBits(
4753 CharUnits FieldOffsetInBytes =
4754 CGM.getContext().toCharUnitsFromBits(FieldOffset);
4755 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4756 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4757
4758 if (NumPaddingBytes.isPositive()) {
4759 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4760 FType = CGM.getContext().getConstantArrayType(
4761 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
4762 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4763 }
4764 }
4765
4766 FType = Type;
4767 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4768 FieldSize = CGM.getContext().getTypeSize(FType);
4769 FieldAlign = CGM.getContext().toBits(Align);
4770
4771 *XOffset = FieldOffset;
4772 llvm::DIType *FieldTy = DBuilder.createMemberType(
4773 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4774 llvm::DINode::FlagZero, WrappedTy);
4775 EltTys.push_back(FieldTy);
4776 FieldOffset += FieldSize;
4777
4778 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4779 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4780 llvm::DINode::FlagZero, nullptr, Elements),
4781 WrappedTy};
4782}
4783
4784llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4785 llvm::Value *Storage,
4786 std::optional<unsigned> ArgNo,
4787 CGBuilderTy &Builder,
4788 const bool UsePointerValue) {
4789 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4790 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4791 if (VD->hasAttr<NoDebugAttr>())
4792 return nullptr;
4793
4794 const bool VarIsArtificial = IsArtificial(VD);
4795
4796 llvm::DIFile *Unit = nullptr;
4797 if (!VarIsArtificial)
4798 Unit = getOrCreateFile(VD->getLocation());
4799 llvm::DIType *Ty;
4800 uint64_t XOffset = 0;
4801 if (VD->hasAttr<BlocksAttr>())
4802 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4803 else
4804 Ty = getOrCreateType(VD->getType(), Unit);
4805
4806 // If there is no debug info for this type then do not emit debug info
4807 // for this variable.
4808 if (!Ty)
4809 return nullptr;
4810
4811 // Get location information.
4812 unsigned Line = 0;
4813 unsigned Column = 0;
4814 if (!VarIsArtificial) {
4815 Line = getLineNumber(VD->getLocation());
4816 Column = getColumnNumber(VD->getLocation());
4817 }
4819 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4820 if (VarIsArtificial)
4821 Flags |= llvm::DINode::FlagArtificial;
4822
4823 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4824
4825 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
4826 AppendAddressSpaceXDeref(AddressSpace, Expr);
4827
4828 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4829 // object pointer flag.
4830 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4831 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
4832 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
4833 Flags |= llvm::DINode::FlagObjectPointer;
4834 }
4835
4836 // Note: Older versions of clang used to emit byval references with an extra
4837 // DW_OP_deref, because they referenced the IR arg directly instead of
4838 // referencing an alloca. Newer versions of LLVM don't treat allocas
4839 // differently from other function arguments when used in a dbg.declare.
4840 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4841 StringRef Name = VD->getName();
4842 if (!Name.empty()) {
4843 // __block vars are stored on the heap if they are captured by a block that
4844 // can escape the local scope.
4845 if (VD->isEscapingByref()) {
4846 // Here, we need an offset *into* the alloca.
4848 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4849 // offset of __forwarding field
4850 offset = CGM.getContext().toCharUnitsFromBits(
4852 Expr.push_back(offset.getQuantity());
4853 Expr.push_back(llvm::dwarf::DW_OP_deref);
4854 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4855 // offset of x field
4856 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4857 Expr.push_back(offset.getQuantity());
4858 }
4859 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4860 // If VD is an anonymous union then Storage represents value for
4861 // all union fields.
4862 const RecordDecl *RD = RT->getDecl();
4863 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4864 // GDB has trouble finding local variables in anonymous unions, so we emit
4865 // artificial local variables for each of the members.
4866 //
4867 // FIXME: Remove this code as soon as GDB supports this.
4868 // The debug info verifier in LLVM operates based on the assumption that a
4869 // variable has the same size as its storage and we had to disable the
4870 // check for artificial variables.
4871 for (const auto *Field : RD->fields()) {
4872 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4873 StringRef FieldName = Field->getName();
4874
4875 // Ignore unnamed fields. Do not ignore unnamed records.
4876 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4877 continue;
4878
4879 // Use VarDecl's Tag, Scope and Line number.
4880 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4881 auto *D = DBuilder.createAutoVariable(
4882 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4883 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4884
4885 // Insert an llvm.dbg.declare into the current block.
4886 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4887 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4888 Column, Scope,
4889 CurInlinedAt),
4890 Builder.GetInsertBlock());
4891 }
4892 }
4893 }
4894
4895 // Clang stores the sret pointer provided by the caller in a static alloca.
4896 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4897 // the address of the variable.
4898 if (UsePointerValue) {
4899 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4900 "Debug info already contains DW_OP_deref.");
4901 Expr.push_back(llvm::dwarf::DW_OP_deref);
4902 }
4903
4904 // Create the descriptor for the variable.
4905 llvm::DILocalVariable *D = nullptr;
4906 if (ArgNo) {
4907 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4908 D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4909 CGM.getLangOpts().Optimize, Flags,
4910 Annotations);
4911 } else {
4912 // For normal local variable, we will try to find out whether 'VD' is the
4913 // copy parameter of coroutine.
4914 // If yes, we are going to use DIVariable of the origin parameter instead
4915 // of creating the new one.
4916 // If no, it might be a normal alloc, we just create a new one for it.
4917
4918 // Check whether the VD is move parameters.
4919 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4920 // The scope of parameter and move-parameter should be distinct
4921 // DISubprogram.
4922 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4923 return nullptr;
4924
4925 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4926 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4927 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4928 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4929 Decl *Decl = DeclGroup.getSingleDecl();
4930 if (VD == dyn_cast_or_null<VarDecl>(Decl))
4931 return true;
4932 }
4933 return false;
4934 });
4935
4936 if (Iter != CoroutineParameterMappings.end()) {
4937 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4938 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4939 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4940 });
4941 if (Iter2 != ParamDbgMappings.end())
4942 return const_cast<llvm::DILocalVariable *>(Iter2->second);
4943 }
4944 return nullptr;
4945 };
4946
4947 // If we couldn't find a move param DIVariable, create a new one.
4948 D = RemapCoroArgToLocalVar();
4949 // Or we will create a new DIVariable for this Decl if D dose not exists.
4950 if (!D)
4951 D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4952 CGM.getLangOpts().Optimize, Flags, Align);
4953 }
4954 // Insert an llvm.dbg.declare into the current block.
4955 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4956 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4957 Column, Scope, CurInlinedAt),
4958 Builder.GetInsertBlock());
4959
4960 return D;
4961}
4962
4963llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4964 llvm::Value *Storage,
4965 std::optional<unsigned> ArgNo,
4966 CGBuilderTy &Builder,
4967 const bool UsePointerValue) {
4968 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4969 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4970 if (BD->hasAttr<NoDebugAttr>())
4971 return nullptr;
4972
4973 // Skip the tuple like case, we don't handle that here
4974 if (isa<DeclRefExpr>(BD->getBinding()))
4975 return nullptr;
4976
4977 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4978 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
4979
4980 // If there is no debug info for this type then do not emit debug info
4981 // for this variable.
4982 if (!Ty)
4983 return nullptr;
4984
4985 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4986 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
4987
4989 AppendAddressSpaceXDeref(AddressSpace, Expr);
4990
4991 // Clang stores the sret pointer provided by the caller in a static alloca.
4992 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4993 // the address of the variable.
4994 if (UsePointerValue) {
4995 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4996 "Debug info already contains DW_OP_deref.");
4997 Expr.push_back(llvm::dwarf::DW_OP_deref);
4998 }
4999
5000 unsigned Line = getLineNumber(BD->getLocation());
5001 unsigned Column = getColumnNumber(BD->getLocation());
5002 StringRef Name = BD->getName();
5003 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5004 // Create the descriptor for the variable.
5005 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5006 Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
5007 llvm::DINode::FlagZero, Align);
5008
5009 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5010 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5011 const unsigned fieldIndex = FD->getFieldIndex();
5012 const clang::CXXRecordDecl *parent =
5013 (const CXXRecordDecl *)FD->getParent();
5014 const ASTRecordLayout &layout =
5015 CGM.getContext().getASTRecordLayout(parent);
5016 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5017 if (FD->isBitField()) {
5018 const CGRecordLayout &RL =
5019 CGM.getTypes().getCGRecordLayout(FD->getParent());
5020 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5021 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5022 // storage.
5023 if (!Info.StorageOffset.isZero()) {
5024 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5025 Expr.push_back(Info.StorageOffset.getQuantity());
5026 }
5027 // Use LLVM_extract_bits to extract the appropriate bits from this
5028 // bitfield.
5029 Expr.push_back(Info.IsSigned
5030 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5031 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5032 Expr.push_back(Info.Offset);
5033 // If we have an oversized bitfield then the value won't be more than
5034 // the size of the type.
5035 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5036 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5037 } else if (fieldOffset != 0) {
5038 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5039 "Unexpected non-bitfield with non-byte-aligned offset");
5040 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5041 Expr.push_back(
5042 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5043 }
5044 }
5045 } else if (const ArraySubscriptExpr *ASE =
5046 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5047 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5048 const uint64_t value = IL->getValue().getZExtValue();
5049 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5050
5051 if (value != 0) {
5052 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5053 Expr.push_back(CGM.getContext()
5054 .toCharUnitsFromBits(value * typeSize)
5055 .getQuantity());
5056 }
5057 }
5058 }
5059
5060 // Insert an llvm.dbg.declare into the current block.
5061 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5062 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5063 Column, Scope, CurInlinedAt),
5064 Builder.GetInsertBlock());
5065
5066 return D;
5067}
5068
5069llvm::DILocalVariable *
5070CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5071 CGBuilderTy &Builder,
5072 const bool UsePointerValue) {
5073 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5074
5075 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5076 for (auto *B : DD->bindings()) {
5077 EmitDeclare(B, Storage, std::nullopt, Builder,
5078 VD->getType()->isReferenceType());
5079 }
5080 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5081 // correspond to a user variable.
5082 return nullptr;
5083 }
5084
5085 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5086}
5087
5089 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5090 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5091
5092 if (D->hasAttr<NoDebugAttr>())
5093 return;
5094
5095 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5096 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5097
5098 // Get location information.
5099 unsigned Line = getLineNumber(D->getLocation());
5100 unsigned Column = getColumnNumber(D->getLocation());
5101
5102 StringRef Name = D->getName();
5103
5104 // Create the descriptor for the label.
5105 auto *L =
5106 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
5107
5108 // Insert an llvm.dbg.label into the current block.
5109 DBuilder.insertLabel(L,
5110 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5111 Scope, CurInlinedAt),
5112 Builder.GetInsertBlock());
5113}
5114
5115llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5116 llvm::DIType *Ty) {
5117 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5118 if (CachedTy)
5119 Ty = CachedTy;
5120 return DBuilder.createObjectPointerType(Ty);
5121}
5122
5124 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5125 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5126 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5127 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5128
5129 if (Builder.GetInsertBlock() == nullptr)
5130 return;
5131 if (VD->hasAttr<NoDebugAttr>())
5132 return;
5133
5134 bool isByRef = VD->hasAttr<BlocksAttr>();
5135
5136 uint64_t XOffset = 0;
5137 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5138 llvm::DIType *Ty;
5139 if (isByRef)
5140 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5141 else
5142 Ty = getOrCreateType(VD->getType(), Unit);
5143
5144 // Self is passed along as an implicit non-arg variable in a
5145 // block. Mark it as the object pointer.
5146 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5147 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5148 Ty = CreateSelfType(VD->getType(), Ty);
5149
5150 // Get location information.
5151 const unsigned Line =
5152 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5153 unsigned Column = getColumnNumber(VD->getLocation());
5154
5155 const llvm::DataLayout &target = CGM.getDataLayout();
5156
5158 target.getStructLayout(blockInfo.StructureType)
5159 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5160
5162 addr.push_back(llvm::dwarf::DW_OP_deref);
5163 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5164 addr.push_back(offset.getQuantity());
5165 if (isByRef) {
5166 addr.push_back(llvm::dwarf::DW_OP_deref);
5167 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5168 // offset of __forwarding field
5169 offset =
5170 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5171 addr.push_back(offset.getQuantity());
5172 addr.push_back(llvm::dwarf::DW_OP_deref);
5173 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5174 // offset of x field
5175 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5176 addr.push_back(offset.getQuantity());
5177 }
5178
5179 // Create the descriptor for the variable.
5180 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5181 auto *D = DBuilder.createAutoVariable(
5182 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5183 Line, Ty, false, llvm::DINode::FlagZero, Align);
5184
5185 // Insert an llvm.dbg.declare into the current block.
5186 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5187 LexicalBlockStack.back(), CurInlinedAt);
5188 auto *Expr = DBuilder.createExpression(addr);
5189 if (InsertPoint)
5190 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
5191 else
5192 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5193}
5194
5195llvm::DILocalVariable *
5197 unsigned ArgNo, CGBuilderTy &Builder,
5198 bool UsePointerValue) {
5199 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5200 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5201}
5202
5203namespace {
5204struct BlockLayoutChunk {
5205 uint64_t OffsetInBits;
5207};
5208bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5209 return l.OffsetInBits < r.OffsetInBits;
5210}
5211} // namespace
5212
5213void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5214 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5215 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5217 // Blocks in OpenCL have unique constraints which make the standard fields
5218 // redundant while requiring size and align fields for enqueue_kernel. See
5219 // initializeForBlockHeader in CGBlocks.cpp
5220 if (CGM.getLangOpts().OpenCL) {
5221 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5222 BlockLayout.getElementOffsetInBits(0),
5223 Unit, Unit));
5224 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5225 BlockLayout.getElementOffsetInBits(1),
5226 Unit, Unit));
5227 } else {
5228 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5229 BlockLayout.getElementOffsetInBits(0),
5230 Unit, Unit));
5231 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5232 BlockLayout.getElementOffsetInBits(1),
5233 Unit, Unit));
5234 Fields.push_back(
5235 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5236 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5237 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5238 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5239 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5240 BlockLayout.getElementOffsetInBits(3),
5241 Unit, Unit));
5242 Fields.push_back(createFieldType(
5243 "__descriptor",
5244 Context.getPointerType(Block.NeedsCopyDispose
5246 : Context.getBlockDescriptorType()),
5247 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5248 }
5249}
5250
5252 StringRef Name,
5253 unsigned ArgNo,
5254 llvm::AllocaInst *Alloca,
5255 CGBuilderTy &Builder) {
5256 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5257 ASTContext &C = CGM.getContext();
5258 const BlockDecl *blockDecl = block.getBlockDecl();
5259
5260 // Collect some general information about the block's location.
5261 SourceLocation loc = blockDecl->getCaretLocation();
5262 llvm::DIFile *tunit = getOrCreateFile(loc);
5263 unsigned line = getLineNumber(loc);
5264 unsigned column = getColumnNumber(loc);
5265
5266 // Build the debug-info type for the block literal.
5267 getDeclContextDescriptor(blockDecl);
5268
5269 const llvm::StructLayout *blockLayout =
5270 CGM.getDataLayout().getStructLayout(block.StructureType);
5271
5273 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5274 fields);
5275
5276 // We want to sort the captures by offset, not because DWARF
5277 // requires this, but because we're paranoid about debuggers.
5279
5280 // 'this' capture.
5281 if (blockDecl->capturesCXXThis()) {
5282 BlockLayoutChunk chunk;
5283 chunk.OffsetInBits =
5284 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5285 chunk.Capture = nullptr;
5286 chunks.push_back(chunk);
5287 }
5288
5289 // Variable captures.
5290 for (const auto &capture : blockDecl->captures()) {
5291 const VarDecl *variable = capture.getVariable();
5292 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5293
5294 // Ignore constant captures.
5295 if (captureInfo.isConstant())
5296 continue;
5297
5298 BlockLayoutChunk chunk;
5299 chunk.OffsetInBits =
5300 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5301 chunk.Capture = &capture;
5302 chunks.push_back(chunk);
5303 }
5304
5305 // Sort by offset.
5306 llvm::array_pod_sort(chunks.begin(), chunks.end());
5307
5308 for (const BlockLayoutChunk &Chunk : chunks) {
5309 uint64_t offsetInBits = Chunk.OffsetInBits;
5310 const BlockDecl::Capture *capture = Chunk.Capture;
5311
5312 // If we have a null capture, this must be the C++ 'this' capture.
5313 if (!capture) {
5314 QualType type;
5315 if (auto *Method =
5316 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5317 type = Method->getThisType();
5318 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5319 type = QualType(RDecl->getTypeForDecl(), 0);
5320 else
5321 llvm_unreachable("unexpected block declcontext");
5322
5323 fields.push_back(createFieldType("this", type, loc, AS_public,
5324 offsetInBits, tunit, tunit));
5325 continue;
5326 }
5327
5328 const VarDecl *variable = capture->getVariable();
5329 StringRef name = variable->getName();
5330
5331 llvm::DIType *fieldType;
5332 if (capture->isByRef()) {
5333 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5334 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5335 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5336 uint64_t xoffset;
5337 fieldType =
5338 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5339 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5340 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5341 PtrInfo.Width, Align, offsetInBits,
5342 llvm::DINode::FlagZero, fieldType);
5343 } else {
5344 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5345 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5346 offsetInBits, Align, tunit, tunit);
5347 }
5348 fields.push_back(fieldType);
5349 }
5350
5351 SmallString<36> typeName;
5352 llvm::raw_svector_ostream(typeName)
5353 << "__block_literal_" << CGM.getUniqueBlockCount();
5354
5355 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5356
5357 llvm::DIType *type =
5358 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5359 CGM.getContext().toBits(block.BlockSize), 0,
5360 llvm::DINode::FlagZero, nullptr, fieldsArray);
5361 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5362
5363 // Get overall information about the block.
5364 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5365 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5366
5367 // Create the descriptor for the parameter.
5368 auto *debugVar = DBuilder.createParameterVariable(
5369 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
5370
5371 // Insert an llvm.dbg.declare into the current block.
5372 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5373 llvm::DILocation::get(CGM.getLLVMContext(), line,
5374 column, scope, CurInlinedAt),
5375 Builder.GetInsertBlock());
5376}
5377
5378llvm::DIDerivedType *
5379CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5380 if (!D || !D->isStaticDataMember())
5381 return nullptr;
5382
5383 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5384 if (MI != StaticDataMemberCache.end()) {
5385 assert(MI->second && "Static data member declaration should still exist");
5386 return MI->second;
5387 }
5388
5389 // If the member wasn't found in the cache, lazily construct and add it to the
5390 // type (used when a limited form of the type is emitted).
5391 auto DC = D->getDeclContext();
5392 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5393 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5394}
5395
5396llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5397 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5398 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5399 llvm::DIGlobalVariableExpression *GVE = nullptr;
5400
5401 for (const auto *Field : RD->fields()) {
5402 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5403 StringRef FieldName = Field->getName();
5404
5405 // Ignore unnamed fields, but recurse into anonymous records.
5406 if (FieldName.empty()) {
5407 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5408 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
5409 Var, DContext);
5410 continue;
5411 }
5412 // Use VarDecl's Tag, Scope and Line number.
5413 GVE = DBuilder.createGlobalVariableExpression(
5414 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5415 Var->hasLocalLinkage());
5416 Var->addDebugInfo(GVE);
5417 }
5418 return GVE;
5419}
5420
5423 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5424 // info we produce in the DWARF, so we can't get Clang's full name back.
5425 // But so long as it's not one of those, it doesn't matter if some sub-type
5426 // of the record (a template parameter) can't be reconstituted - because the
5427 // un-reconstitutable type itself will carry its own name.
5428 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5429 if (!RD)
5430 return false;
5431 if (!RD->getIdentifier())
5432 return true;
5433 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5434 if (!TSpecial)
5435 return false;
5436 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5437}
5439 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5440 switch (TA.getKind()) {
5441 case TemplateArgument::Pack:
5442 return ReferencesAnonymousEntity(TA.getPackAsArray());
5443 case TemplateArgument::Type: {
5444 struct ReferencesAnonymous
5445 : public RecursiveASTVisitor<ReferencesAnonymous> {
5446 bool RefAnon = false;
5447 bool VisitRecordType(RecordType *RT) {
5448 if (ReferencesAnonymousEntity(RT)) {
5449 RefAnon = true;
5450 return false;
5451 }
5452 return true;
5453 }
5454 };
5455 ReferencesAnonymous RT;
5456 RT.TraverseType(TA.getAsType());
5457 if (RT.RefAnon)
5458 return true;
5459 break;
5460 }
5461 default:
5462 break;
5463 }
5464 return false;
5465 });
5466}
5467namespace {
5468struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5469 bool Reconstitutable = true;
5470 bool VisitVectorType(VectorType *FT) {
5471 Reconstitutable = false;
5472 return false;
5473 }
5474 bool VisitAtomicType(AtomicType *FT) {
5475 Reconstitutable = false;
5476 return false;
5477 }
5478 bool VisitType(Type *T) {
5479 // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5480 // the DWARF, only the byte width.
5481 if (T->isBitIntType()) {
5482 Reconstitutable = false;
5483 return false;
5484 }
5485 return true;
5486 }
5487 bool TraverseEnumType(EnumType *ET) {
5488 // Unnamed enums can't be reconstituted due to a lack of column info we
5489 // produce in the DWARF, so we can't get Clang's full name back.
5490 if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5491 if (!ED->getIdentifier()) {
5492 Reconstitutable = false;
5493 return false;
5494 }
5495 if (!ED->isExternallyVisible()) {
5496 Reconstitutable = false;
5497 return false;
5498 }
5499 }
5500 return true;
5501 }
5502 bool VisitFunctionProtoType(FunctionProtoType *FT) {
5503 // noexcept is not encoded in DWARF, so the reversi
5504 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5505 Reconstitutable &= !FT->getNoReturnAttr();
5506 return Reconstitutable;
5507 }
5508 bool VisitRecordType(RecordType *RT) {
5509 if (ReferencesAnonymousEntity(RT)) {
5510 Reconstitutable = false;
5511 return false;
5512 }
5513 return true;
5514 }
5515};
5516} // anonymous namespace
5517
5518// Test whether a type name could be rebuilt from emitted debug info.
5520 ReconstitutableType T;
5521 T.TraverseType(QT);
5522 return T.Reconstitutable;
5523}
5524
5525bool CGDebugInfo::HasReconstitutableArgs(
5526 ArrayRef<TemplateArgument> Args) const {
5527 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5528 switch (TA.getKind()) {
5529 case TemplateArgument::Template:
5530 // Easy to reconstitute - the value of the parameter in the debug
5531 // info is the string name of the template. The template name
5532 // itself won't benefit from any name rebuilding, but that's a
5533 // representational limitation - maybe DWARF could be
5534 // changed/improved to use some more structural representation.
5535 return true;
5536 case TemplateArgument::Declaration:
5537 // Reference and pointer non-type template parameters point to
5538 // variables, functions, etc and their value is, at best (for
5539 // variables) represented as an address - not a reference to the
5540 // DWARF describing the variable/function/etc. This makes it hard,
5541 // possibly impossible to rebuild the original name - looking up
5542 // the address in the executable file's symbol table would be
5543 // needed.
5544 return false;
5545 case TemplateArgument::NullPtr:
5546 // These could be rebuilt, but figured they're close enough to the
5547 // declaration case, and not worth rebuilding.
5548 return false;
5549 case TemplateArgument::Pack:
5550 // A pack is invalid if any of the elements of the pack are
5551 // invalid.
5552 return HasReconstitutableArgs(TA.getPackAsArray());
5553 case TemplateArgument::Integral:
5554 // Larger integers get encoded as DWARF blocks which are a bit
5555 // harder to parse back into a large integer, etc - so punting on
5556 // this for now. Re-parsing the integers back into APInt is
5557 // probably feasible some day.
5558 return TA.getAsIntegral().getBitWidth() <= 64 &&
5559 IsReconstitutableType(TA.getIntegralType());
5560 case TemplateArgument::StructuralValue:
5561 return false;
5562 case TemplateArgument::Type:
5563 return IsReconstitutableType(TA.getAsType());
5564 case TemplateArgument::Expression:
5565 return IsReconstitutableType(TA.getAsExpr()->getType());
5566 default:
5567 llvm_unreachable("Other, unresolved, template arguments should "
5568 "not be seen here");
5569 }
5570 });
5571}
5572
5573std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5574 std::string Name;
5575 llvm::raw_string_ostream OS(Name);
5576 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5577 if (!ND)
5578 return Name;
5579 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5580 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5581
5583 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
5584
5585 std::optional<TemplateArgs> Args;
5586
5587 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5588 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5589 Args = GetTemplateArgs(RD);
5590 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5591 Args = GetTemplateArgs(FD);
5592 auto NameKind = ND->getDeclName().getNameKind();
5593 IsOperatorOverload |=
5596 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5597 Args = GetTemplateArgs(VD);
5598 }
5599
5600 // A conversion operator presents complications/ambiguity if there's a
5601 // conversion to class template that is itself a template, eg:
5602 // template<typename T>
5603 // operator ns::t1<T, int>();
5604 // This should be named, eg: "operator ns::t1<float, int><float>"
5605 // (ignoring clang bug that means this is currently "operator t1<float>")
5606 // but if the arguments were stripped, the consumer couldn't differentiate
5607 // whether the template argument list for the conversion type was the
5608 // function's argument list (& no reconstitution was needed) or not.
5609 // This could be handled if reconstitutable names had a separate attribute
5610 // annotating them as such - this would remove the ambiguity.
5611 //
5612 // Alternatively the template argument list could be parsed enough to check
5613 // whether there's one list or two, then compare that with the DWARF
5614 // description of the return type and the template argument lists to determine
5615 // how many lists there should be and if one is missing it could be assumed(?)
5616 // to be the function's template argument list & then be rebuilt.
5617 //
5618 // Other operator overloads that aren't conversion operators could be
5619 // reconstituted but would require a bit more nuance about detecting the
5620 // difference between these different operators during that rebuilding.
5621 bool Reconstitutable =
5622 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5623
5624 PrintingPolicy PP = getPrintingPolicy();
5625
5626 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
5627 !Reconstitutable) {
5628 ND->getNameForDiagnostic(OS, PP, Qualified);
5629 } else {
5630 bool Mangled = TemplateNamesKind ==
5631 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
5632 // check if it's a template
5633 if (Mangled)
5634 OS << "_STN|";
5635
5636 OS << ND->getDeclName();
5637 std::string EncodedOriginalName;
5638 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5639 EncodedOriginalNameOS << ND->getDeclName();
5640
5641 if (Mangled) {
5642 OS << "|";
5643 printTemplateArgumentList(OS, Args->Args, PP);
5644 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5645#ifndef NDEBUG
5646 std::string CanonicalOriginalName;
5647 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5648 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5649 assert(EncodedOriginalName == CanonicalOriginalName);
5650#endif
5651 }
5652 }
5653 return Name;
5654}
5655
5656void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5657 const VarDecl *D) {
5658 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5659 if (D->hasAttr<NoDebugAttr>())
5660 return;
5661
5662 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5663 return GetName(D, true);
5664 });
5665
5666 // If we already created a DIGlobalVariable for this declaration, just attach
5667 // it to the llvm::GlobalVariable.
5668 auto Cached = DeclCache.find(D->getCanonicalDecl());
5669 if (Cached != DeclCache.end())
5670 return Var->addDebugInfo(
5671 cast<llvm::DIGlobalVariableExpression>(Cached->second));
5672
5673 // Create global variable debug descriptor.
5674 llvm::DIFile *Unit = nullptr;
5675 llvm::DIScope *DContext = nullptr;
5676 unsigned LineNo;
5677 StringRef DeclName, LinkageName;
5678 QualType T;
5679 llvm::MDTuple *TemplateParameters = nullptr;
5680 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5681 TemplateParameters, DContext);
5682
5683 // Attempt to store one global variable for the declaration - even if we
5684 // emit a lot of fields.
5685 llvm::DIGlobalVariableExpression *GVE = nullptr;
5686
5687 // If this is an anonymous union then we'll want to emit a global
5688 // variable for each member of the anonymous union so that it's possible
5689 // to find the name of any field in the union.
5690 if (T->isUnionType() && DeclName.empty()) {
5691 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5692 assert(RD->isAnonymousStructOrUnion() &&
5693 "unnamed non-anonymous struct or union?");
5694 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5695 } else {
5696 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5697
5699 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
5700 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5701 if (D->hasAttr<CUDASharedAttr>())
5702 AddressSpace =
5704 else if (D->hasAttr<CUDAConstantAttr>())
5705 AddressSpace =
5707 }
5708 AppendAddressSpaceXDeref(AddressSpace, Expr);
5709
5710 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5711 GVE = DBuilder.createGlobalVariableExpression(
5712 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5713 Var->hasLocalLinkage(), true,
5714 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5715 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5716 Align, Annotations);
5717 Var->addDebugInfo(GVE);
5718 }
5719 DeclCache[D->getCanonicalDecl()].reset(GVE);
5720}
5721
5723 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5724 if (VD->hasAttr<NoDebugAttr>())
5725 return;
5726 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5727 return GetName(VD, true);
5728 });
5729
5730 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5731 // Create the descriptor for the variable.
5732 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5733 StringRef Name = VD->getName();
5734 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5735
5736 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5737 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5738 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5739
5740 if (CGM.getCodeGenOpts().EmitCodeView) {
5741 // If CodeView, emit enums as global variables, unless they are defined
5742 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5743 // enums in classes, and because it is difficult to attach this scope
5744 // information to the global variable.
5745 if (isa<RecordDecl>(ED->getDeclContext()))
5746 return;
5747 } else {
5748 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5749 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5750 // first time `ZERO` is referenced in a function.
5751 llvm::DIType *EDTy =
5752 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5753 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5754 (void)EDTy;
5755 return;
5756 }
5757 }
5758
5759 // Do not emit separate definitions for function local consts.
5760 if (isa<FunctionDecl>(VD->getDeclContext()))
5761 return;
5762
5763 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5764 auto *VarD = dyn_cast<VarDecl>(VD);
5765 if (VarD && VarD->isStaticDataMember()) {
5766 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5767 getDeclContextDescriptor(VarD);
5768 // Ensure that the type is retained even though it's otherwise unreferenced.
5769 //
5770 // FIXME: This is probably unnecessary, since Ty should reference RD
5771 // through its scope.
5772 RetainedTypes.push_back(
5774
5775 return;
5776 }
5777 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5778
5779 auto &GV = DeclCache[VD];
5780 if (GV)
5781 return;
5782
5783 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
5784 llvm::MDTuple *TemplateParameters = nullptr;
5785
5786 if (isa<VarTemplateSpecializationDecl>(VD))
5787 if (VarD) {
5788 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5789 TemplateParameters = parameterNodes.get();
5790 }
5791
5792 GV.reset(DBuilder.createGlobalVariableExpression(
5793 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5794 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5795 TemplateParameters, Align));
5796}
5797
5798void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5799 const VarDecl *D) {
5800 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5801 if (D->hasAttr<NoDebugAttr>())
5802 return;
5803
5804 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5805 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5806 StringRef Name = D->getName();
5807 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5808
5809 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5810 llvm::DIGlobalVariableExpression *GVE =
5811 DBuilder.createGlobalVariableExpression(
5812 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5813 Ty, false, false, nullptr, nullptr, nullptr, Align);
5814 Var->addDebugInfo(GVE);
5815}
5816
5818 llvm::Instruction *Value, QualType Ty) {
5819 // Only when -g2 or above is specified, debug info for variables will be
5820 // generated.
5821 if (CGM.getCodeGenOpts().getDebugInfo() <=
5822 llvm::codegenoptions::DebugLineTablesOnly)
5823 return;
5824
5825 llvm::DILocation *DIL = Value->getDebugLoc().get();
5826 if (!DIL)
5827 return;
5828
5829 llvm::DIFile *Unit = DIL->getFile();
5830 llvm::DIType *Type = getOrCreateType(Ty, Unit);
5831
5832 // Check if Value is already a declared variable and has debug info, in this
5833 // case we have nothing to do. Clang emits a declared variable as alloca, and
5834 // it is loaded upon use, so we identify such pattern here.
5835 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
5836 llvm::Value *Var = Load->getPointerOperand();
5837 // There can be implicit type cast applied on a variable if it is an opaque
5838 // ptr, in this case its debug info may not match the actual type of object
5839 // being used as in the next instruction, so we will need to emit a pseudo
5840 // variable for type-casted value.
5841 auto DeclareTypeMatches = [&](auto *DbgDeclare) {
5842 return DbgDeclare->getVariable()->getType() == Type;
5843 };
5844 if (any_of(llvm::findDbgDeclares(Var), DeclareTypeMatches) ||
5845 any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
5846 return;
5847 }
5848
5849 llvm::DILocalVariable *D =
5850 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
5851 Type, false, llvm::DINode::FlagArtificial);
5852
5853 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
5854 DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,
5855 &**InsertPoint);
5856 }
5857}
5858
5859void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5860 const GlobalDecl GD) {
5861
5862 assert(GV);
5863
5865 return;
5866
5867 const auto *D = cast<ValueDecl>(GD.getDecl());
5868 if (D->hasAttr<NoDebugAttr>())
5869 return;
5870
5871 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5872 llvm::DINode *DI;
5873
5874 if (!AliaseeDecl)
5875 // FIXME: Aliasee not declared yet - possibly declared later
5876 // For example,
5877 //
5878 // 1 extern int newname __attribute__((alias("oldname")));
5879 // 2 int oldname = 1;
5880 //
5881 // No debug info would be generated for 'newname' in this case.
5882 //
5883 // Fix compiler to generate "newname" as imported_declaration
5884 // pointing to the DIE of "oldname".
5885 return;
5886 if (!(DI = getDeclarationOrDefinition(
5887 AliaseeDecl.getCanonicalDecl().getDecl())))
5888 return;
5889
5890 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5891 auto Loc = D->getLocation();
5892
5893 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5894 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5895
5896 // Record this DIE in the cache for nested declaration reference.
5897 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5898}
5899
5900void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
5901 const StringLiteral *S) {
5902 SourceLocation Loc = S->getStrTokenLoc(0);
5904 if (!PLoc.isValid())
5905 return;
5906
5907 llvm::DIFile *File = getOrCreateFile(Loc);
5908 llvm::DIGlobalVariableExpression *Debug =
5909 DBuilder.createGlobalVariableExpression(
5910 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
5911 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
5912 GV->addDebugInfo(Debug);
5913}
5914
5915llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5916 if (!LexicalBlockStack.empty())
5917 return LexicalBlockStack.back();
5918 llvm::DIScope *Mod = getParentModuleOrNull(D);
5919 return getContextDescriptor(D, Mod ? Mod : TheCU);
5920}
5921
5924 return;
5925 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5926 if (!NSDecl->isAnonymousNamespace() ||
5927 CGM.getCodeGenOpts().DebugExplicitImport) {
5928 auto Loc = UD.getLocation();
5929 if (!Loc.isValid())
5930 Loc = CurLoc;
5931 DBuilder.createImportedModule(
5932 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5933 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5934 }
5935}
5936
5938 if (llvm::DINode *Target =
5939 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5940 auto Loc = USD.getLocation();
5941 DBuilder.createImportedDeclaration(
5942 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5943 getOrCreateFile(Loc), getLineNumber(Loc));
5944 }
5945}
5946
5949 return;
5950 assert(UD.shadow_size() &&
5951 "We shouldn't be codegening an invalid UsingDecl containing no decls");
5952
5953 for (const auto *USD : UD.shadows()) {
5954 // FIXME: Skip functions with undeduced auto return type for now since we
5955 // don't currently have the plumbing for separate declarations & definitions
5956 // of free functions and mismatched types (auto in the declaration, concrete
5957 // return type in the definition)
5958 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5959 if (const auto *AT = FD->getType()
5960 ->castAs<FunctionProtoType>()
5962 if (AT->getDeducedType().isNull())
5963 continue;
5964
5965 EmitUsingShadowDecl(*USD);
5966 // Emitting one decl is sufficient - debuggers can detect that this is an
5967 // overloaded name & provide lookup for all the overloads.
5968 break;
5969 }
5970}
5971
5974 return;
5975 assert(UD.shadow_size() &&
5976 "We shouldn't be codegening an invalid UsingEnumDecl"
5977 " containing no decls");
5978
5979 for (const auto *USD : UD.shadows())
5980 EmitUsingShadowDecl(*USD);
5981}
5982
5984 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5985 return;
5986 if (Module *M = ID.getImportedModule()) {
5987 auto Info = ASTSourceDescriptor(*M);
5988 auto Loc = ID.getLocation();
5989 DBuilder.createImportedDeclaration(
5990 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5991 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5992 getLineNumber(Loc));
5993 }
5994}
5995
5996llvm::DIImportedEntity *
5999 return nullptr;
6000 auto &VH = NamespaceAliasCache[&NA];
6001 if (VH)
6002 return cast<llvm::DIImportedEntity>(VH);
6003 llvm::DIImportedEntity *R;
6004 auto Loc = NA.getLocation();
6005 if (const auto *Underlying =
6006 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6007 // This could cache & dedup here rather than relying on metadata deduping.
6008 R = DBuilder.createImportedDeclaration(
6009 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6010 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6011 getLineNumber(Loc), NA.getName());
6012 else
6013 R = DBuilder.createImportedDeclaration(
6014 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6015 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6016 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6017 VH.reset(R);
6018 return R;
6019}
6020
6021llvm::DINamespace *
6022CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6023 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6024 // if necessary, and this way multiple declarations of the same namespace in
6025 // different parent modules stay distinct.
6026 auto I = NamespaceCache.find(NSDecl);
6027 if (I != NamespaceCache.end())
6028 return cast<llvm::DINamespace>(I->second);
6029
6030 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6031 // Don't trust the context if it is a DIModule (see comment above).
6032 llvm::DINamespace *NS =
6033 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6034 NamespaceCache[NSDecl].reset(NS);
6035 return NS;
6036}
6037
6038void CGDebugInfo::setDwoId(uint64_t Signature) {
6039 assert(TheCU && "no main compile unit");
6040 TheCU->setDWOId(Signature);
6041}
6042
6044 // Creating types might create further types - invalidating the current
6045 // element and the size(), so don't cache/reference them.
6046 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6047 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6048 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6049 ? CreateTypeDefinition(E.Type, E.Unit)
6050 : E.Decl;
6051 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6052 }
6053
6054 // Add methods to interface.
6055 for (const auto &P : ObjCMethodCache) {
6056 if (P.second.empty())
6057 continue;
6058
6059 QualType QTy(P.first->getTypeForDecl(), 0);
6060 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6061 assert(It != TypeCache.end());
6062
6063 llvm::DICompositeType *InterfaceDecl =
6064 cast<llvm::DICompositeType>(It->second);
6065
6066 auto CurElts = InterfaceDecl->getElements();
6067 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6068
6069 // For DWARF v4 or earlier, only add objc_direct methods.
6070 for (auto &SubprogramDirect : P.second)
6071 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6072 EltTys.push_back(SubprogramDirect.getPointer());
6073
6074 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6075 DBuilder.replaceArrays(InterfaceDecl, Elements);
6076 }
6077
6078 for (const auto &P : ReplaceMap) {
6079 assert(P.second);
6080 auto *Ty = cast<llvm::DIType>(P.second);
6081 assert(Ty->isForwardDecl());
6082
6083 auto It = TypeCache.find(P.first);
6084 assert(It != TypeCache.end());
6085 assert(It->second);
6086
6087 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6088 cast<llvm::DIType>(It->second));
6089 }
6090
6091 for (const auto &P : FwdDeclReplaceMap) {
6092 assert(P.second);
6093 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6094 llvm::Metadata *Repl;
6095
6096 auto It = DeclCache.find(P.first);
6097 // If there has been no definition for the declaration, call RAUW
6098 // with ourselves, that will destroy the temporary MDNode and
6099 // replace it with a standard one, avoiding leaking memory.
6100 if (It == DeclCache.end())
6101 Repl = P.second;
6102 else
6103 Repl = It->second;
6104
6105 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6106 Repl = GVE->getVariable();
6107 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6108 }
6109
6110 // We keep our own list of retained types, because we need to look
6111 // up the final type in the type cache.
6112 for (auto &RT : RetainedTypes)
6113 if (auto MD = TypeCache[RT])
6114 DBuilder.retainType(cast<llvm::DIType>(MD));
6115
6116 DBuilder.finalize();
6117}
6118
6119// Don't ignore in case of explicit cast where it is referenced indirectly.
6122 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6123 DBuilder.retainType(DieTy);
6124}
6125
6128 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6129 DBuilder.retainType(DieTy);
6130}
6131
6133 if (LexicalBlockStack.empty())
6134 return llvm::DebugLoc();
6135
6136 llvm::MDNode *Scope = LexicalBlockStack.back();
6137 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6138 getColumnNumber(Loc), Scope);
6139}
6140
6141llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6142 // Call site-related attributes are only useful in optimized programs, and
6143 // when there's a possibility of debugging backtraces.
6144 if (!CGM.getLangOpts().Optimize ||
6145 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6146 DebugKind == llvm::codegenoptions::LocTrackingOnly)
6147 return llvm::DINode::FlagZero;
6148
6149 // Call site-related attributes are available in DWARF v5. Some debuggers,
6150 // while not fully DWARF v5-compliant, may accept these attributes as if they
6151 // were part of DWARF v4.
6152 bool SupportsDWARFv4Ext =
6153 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6154 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6155 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6156
6157 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6158 return llvm::DINode::FlagZero;
6159
6160 return llvm::DINode::FlagAllCallsDescribed;
6161}
6162
6163llvm::DIExpression *
6164CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6165 const APValue &Val) {
6166 // FIXME: Add a representation for integer constants wider than 64 bits.
6167 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6168 return nullptr;
6169
6170 if (Val.isFloat())
6171 return DBuilder.createConstantValueExpression(
6172 Val.getFloat().bitcastToAPInt().getZExtValue());
6173
6174 if (!Val.isInt())
6175 return nullptr;
6176
6177 llvm::APSInt const &ValInt = Val.getInt();
6178 std::optional<uint64_t> ValIntOpt;
6179 if (ValInt.isUnsigned())
6180 ValIntOpt = ValInt.tryZExtValue();
6181 else if (auto tmp = ValInt.trySExtValue())
6182 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6183 // use std::optional::transform
6184 ValIntOpt = static_cast<uint64_t>(*tmp);
6185
6186 if (ValIntOpt)
6187 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6188
6189 return nullptr;
6190}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
#define SM(sm)
Definition: Cuda.cpp:84
static bool IsReconstitutableType(QualType QT)
static void stripUnusedQualifiers(Qualifiers &Q)
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU)
static bool IsArtificial(VarDecl const *VD)
Returns true if VD is a compiler-generated variable and should be treated as artificial for the purpo...
Definition: CGDebugInfo.cpp:99
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind, bool DebugTypeExtRefs, const RecordDecl *RD, const LangOptions &LangOpts)
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, const RecordDecl *RD)
Convert an AccessSpecifier into the corresponding DINode flag.
static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func)
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C)
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD)
static llvm::SmallVector< TemplateArgument > GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty)
static bool isFunctionLocalClass(const CXXRecordDecl *RD)
isFunctionLocalClass - Return true if CXXRecordDecl is defined inside a function.
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:77
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, CXXRecordDecl::method_iterator End)
static bool canUseCtorHoming(const CXXRecordDecl *RD)
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Getter)
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD)
Return true if the class or any of its methods are marked dllimport.
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:59
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Setter)
static bool isDefinedInClangModule(const RecordDecl *RD)
Does a type definition exist in an imported clang module?
static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q)
static bool IsDecomposedVarDecl(VarDecl const *VD)
Returns true if VD is a a holding variable (aka a VarDecl retrieved using BindingDecl::getHoldingVar)...
Definition: CGDebugInfo.cpp:83
static SmallString< 256 > getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static unsigned getDwarfCC(CallingConv CC)
static bool ReferencesAnonymousEntity(ArrayRef< TemplateArgument > Args)
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
int Category
Definition: Format.cpp:3054
StringRef Identifier
Definition: Format.cpp:3059
unsigned Iter
Definition: HTMLLogger.cpp:153
llvm::MachO::Target Target
Definition: MachO.h:51
constexpr llvm::StringRef ClangTrapPrefix
Definition: ModuleBuilder.h:32
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2890
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:465
bool isFloat() const
Definition: APValue.h:444
bool isInt() const
Definition: APValue.h:443
APFloat & getFloat()
Definition: APValue.h:479
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
SourceManager & getSourceManager()
Definition: ASTContext.h:741
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getRecordType(const RecordDecl *Decl) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getEnumType(const EnumDecl *Decl) const
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;.
Definition: ASTContext.h:2077
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1161
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2206
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType CharTy
Definition: ASTContext.h:1162
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
CanQualType IntTy
Definition: ASTContext.h:1169
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1274
unsigned getTargetAddressSpace(LangAS AS) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2513
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:324
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:234
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:288
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
Definition: RecordLayout.h:242
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
ASTFileSignature getSignature() const
std::string getModuleName() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
const BTFTypeTagAttr * getAttr() const
Definition: Type.h:6231
QualType getWrappedType() const
Definition: Type.h:6230
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3513
shadow_range shadows() const
Definition: DeclCXX.h:3501
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition: DeclCXX.h:4149
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
bool isUnsigned() const
Definition: Type.h:7824
A class which contains all the information about a particular captured value.
Definition: Decl.h:4480
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition: Decl.h:4505
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition: Decl.h:4495
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:4501
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
Pointer to a block type.
Definition: Type.h:3408
QualType getPointeeType() const
Definition: Type.h:3420
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3328
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2620
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isStatic() const
Definition: DeclCXX.cpp:2280
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1155
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1119
method_range methods() const
Definition: DeclCXX.h:662
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1267
method_iterator method_begin() const
Method begin iterator.
Definition: DeclCXX.h:668
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
base_class_range vbases()
Definition: DeclCXX.h:637
ctor_range ctors() const
Definition: DeclCXX.h:682
bool isDynamicClass() const
Definition: DeclCXX.h:586
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool hasDefinition() const
Definition: DeclCXX.h:572
method_iterator method_end() const
Method past-the-end iterator.
Definition: DeclCXX.h:673
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1113
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:618
A wrapper class around a pointer that always points to its canonical declaration.
Definition: Redeclarable.h:348
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Represents a class template specialization, which refers to a class template with a given set of temp...
llvm::SmallVector< std::pair< std::string, std::string >, 0 > DebugPrefixMap
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
bool hasMaybeUnusedDebugInfo() const
Check if maybe unused type info should be emitted.
ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn)
Set up the CodeGenFunction's DebugInfo to produce inline locations for the function InlinedFn.
~ApplyInlineDebugLocation()
Restore everything back to the original state.
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:156
unsigned CXXThisIndex
The field index of 'this' within the block, if there is one.
Definition: CGBlocks.h:162
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:305
llvm::StructType * StructureType
Definition: CGBlocks.h:276
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:296
virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD)
Get the ABI-specific "this" parameter adjustment to apply in the prologue of a virtual function.
Definition: CGCXXABI.h:415
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:161
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:105
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:114
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:109
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
llvm::MDNode * getInlinedAt() const
Definition: CGDebugInfo.h:460
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate a change in line/column information in the source file.
void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder)
Emit call to llvm.dbg.label for an label.
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
void setInlinedAt(llvm::MDNode *InlinedAt)
Update the current inline scope.
Definition: CGDebugInfo.h:457
void completeUnusedClass(const CXXRecordDecl &D)
void EmitUsingShadowDecl(const UsingShadowDecl &USD)
Emit a shadow decl brought in by a using or using-enum.
void EmitUsingEnumDecl(const UsingEnumDecl &UD)
Emit C++ using-enum declaration.
void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn)
Constructs the debug code for exiting a function.
void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, QualType CalleeType, const FunctionDecl *CalleeDecl)
Emit debug info for an extern function being called.
void EmitUsingDecl(const UsingDecl &UD)
Emit C++ using declaration.
llvm::DIMacroFile * CreateTempMacroFile(llvm::DIMacroFile *Parent, SourceLocation LineLoc, SourceLocation FileLoc)
Create debug info for a file referenced by an #include directive.
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void emitFunctionStart(GlobalDecl GD, SourceLocation Loc, SourceLocation ScopeLoc, QualType FnType, llvm::Function *Fn, bool CurFnIsThunk)
Emit a call to llvm.dbg.function.start to indicate start of a new function.
llvm::DILocalVariable * EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder, bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an argument variable declaration.
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
void EmitUsingDirective(const UsingDirectiveDecl &UD)
Emit C++ using directive.
void completeRequiredType(const RecordDecl *RD)
void EmitAndRetainType(QualType Ty)
Emit the type even if it might not be used.
void EmitInlineFunctionEnd(CGBuilderTy &Builder)
End an inlined function scope.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder, const bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an automatic variable declaration.
void completeClassData(const RecordDecl *RD)
void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD)
Start a new scope for an inlined function.
void EmitImportDecl(const ImportDecl &ID)
Emit an @import declaration.
void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, StringRef Name, unsigned ArgNo, llvm::AllocaInst *LocalAddr, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for the block-literal argument to a block invocation function.
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc)
CGDebugInfo(CodeGenModule &CGM)
void completeClass(const RecordDecl *RD)
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack.
void setLocation(SourceLocation Loc)
Update the current source location.
llvm::DIMacro * CreateMacro(llvm::DIMacroFile *Parent, unsigned MType, SourceLocation LineLoc, StringRef Name, StringRef Value)
Create debug info for a macro defined by a #define directive or a macro undefined by a #undef directi...
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value, QualType Ty)
Emit a pseudo variable and debug info for an intermediate value if it does not correspond to a variab...
std::string remapDIPath(StringRef) const
Remap a given path with the current debug prefix map.
void EmitExplicitCastType(QualType Ty)
Emit the type explicitly casted to.
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
void setDwoId(uint64_t Signature)
Module debugging: Support for building PCMs.
QualType getFunctionType(const FunctionDecl *FD, QualType RetTy, const SmallVectorImpl< const VarDecl * > &Args)
llvm::DIType * getOrCreateInterfaceType(QualType Ty, SourceLocation Loc)
Emit an Objective-C interface type standalone debug info.
void completeType(const EnumDecl *ED)
void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder, const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint=nullptr)
Emit call to llvm.dbg.declare for an imported variable declaration in a block.
llvm::DIImportedEntity * EmitNamespaceAlias(const NamespaceAliasDecl &NA)
Emit C++ namespace alias.
unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar)
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
This class organizes the cross-function state that is used while generating LLVM code.
const PreprocessorOptions & getPreprocessorOpts() const
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
llvm::Module & getModule() const
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const LangOptions & getLangOpts() const
int getUniqueBlockCount()
Fetches the global unique block count.
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
CGCXXABI & getCXXABI() const
ItaniumVTableContext & getItaniumVTableContext()
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
MicrosoftVTableContext & getMicrosoftVTableContext()
const HeaderSearchOptions & getHeaderSearchOpts() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::LLVMContext & getLLVMContext()
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
Definition: CGVTables.cpp:1080
const GlobalDecl getMangledNameDecl(StringRef)
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
llvm::Constant * getPointer() const
Definition: Address.h:306
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
virtual bool shouldEmitDWARFBitFieldSeparators() const
Definition: TargetInfo.h:400
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1519
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:534
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:786
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.cpp:118
bool isObjCZeroArgSelector() const
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
bool isObjCOneArgSelector() const
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
Represents an enum.
Definition: Decl.h:3847
enumerator_range enumerators() const
Definition: Decl.h:3980
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
EnumDecl * getDefinition() const
Definition: Decl.h:3950
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4654
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Represents a function declaration or definition.
Definition: Decl.h:1935
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3531
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4182
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1951
bool isStatic() const
Definition: Decl.h:2804
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
QualType desugar() const
Definition: Type.h:5646
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5382
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:527
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4651
CallingConv getCallConv() const
Definition: Type.h:4654
QualType getReturnType() const
Definition: Type.h:4643
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:94
DynamicInitKind getDynamicInitKind() const
Definition: GlobalDecl.h:115
const Decl * getDecl() const
Definition: GlobalDecl.h:103
QualType getWrappedType() const
Definition: Type.h:6293
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
unsigned ModuleFileHomeIsCwd
Set the base path of a built module file to be the current working directory.
One of these records is kept for each identifier that is lexed.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4786
bool isPreprocessed() const
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
Represents the declaration of a label.
Definition: Decl.h:503
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:547
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
Definition: LangOptions.h:610
virtual std::string getLambdaString(const CXXRecordDecl *Lambda)=0
virtual void mangleCXXRTTIName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:5157
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
Describes a module or submodule.
Definition: Module.h:115
Module * Parent
The parent of this module.
Definition: Module.h:164
std::string Name
The name of this module.
Definition: Module.h:118
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:296
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1818
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1675
bool isExternallyVisible() const
Definition: Decl.h:412
Represents a C++ namespace alias.
Definition: DeclCXX.h:3138
NamedDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition: DeclCXX.h:3233
Represent a C++ namespace.
Definition: Decl.h:551
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:607
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1627
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:936
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:869
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1209
Represents a pointer to an Objective C object.
Definition: Type.h:7580
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7655
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7592
Represents a class type in Objective C.
Definition: Type.h:7326
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7388
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
Represents a type parameter type in Objective C.
Definition: Type.h:7252
ObjCTypeParamDecl * getDecl() const
Definition: Type.h:7294
Represents a parameter to a function.
Definition: Decl.h:1725
PipeType - OpenCL20.
Definition: Type.h:7780
QualType getElementType() const
Definition: Type.h:7791
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
bool isValid() const
bool isInvalid() const
Return true if this object is invalid or uninitialized.
FileID getFileID() const
A (possibly-)qualified type.
Definition: Type.h:929
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1056
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
void * getAsOpaquePtr() const
Definition: Type.h:976
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7871
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7878
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
The collection of all-type qualifiers we support.
Definition: Type.h:324
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:377
void removeObjCLifetime()
Definition: Type.h:544
bool hasConst() const
Definition: Type.h:450
bool hasRestrict() const
Definition: Type.h:470
void removeObjCGCAttr()
Definition: Type.h:516
void removeUnaligned()
Definition: Type.h:508
void removeConst()
Definition: Type.h:452
void removeRestrict()
Definition: Type.h:472
void removeAddressSpace()
Definition: Type.h:589
bool hasVolatile() const
Definition: Type.h:460
bool empty() const
Definition: Type.h:640
void removeVolatile()
Definition: Type.h:462
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4148
field_iterator field_end() const
Definition: Decl.h:4357
field_range fields() const
Definition: Decl.h:4354
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4339
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4200
field_iterator field_begin() const
Definition: Decl.cpp:5092
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
QualType getPointeeType() const
Definition: Type.h:3457
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static SmallString< 64 > constructSetterName(StringRef Name)
Return the default setter name for the given identifier.
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Stmt - This represents one statement.
Definition: Stmt.h:84
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3667
bool isStruct() const
Definition: Decl.h:3767
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3792
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3676
bool isUnion() const
Definition: Decl.h:3770
bool isInterface() const
Definition: Decl.h:3768
bool isClass() const
Definition: Decl.h:3769
TagDecl * getDecl() const
Definition: Type.cpp:4122
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
virtual std::optional< unsigned > getDWARFAddressSpace(unsigned AddressSpace) const
Definition: TargetInfo.h:1802
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
virtual unsigned getVtblPtrAddressSpace() const
Definition: TargetInfo.h:1792
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition: TargetInfo.h:482
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
void print(raw_ostream &OS, const PrintingPolicy &Policy, Qualified Qual=Qualified::AsWritten) const
Print the template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:142
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
QualType getAliasedType() const
Get the aliased type, if this is a specialization of a type alias template.
Definition: Type.cpp:4397
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6729
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6727
bool isTypeAlias() const
Determine if this template specialization type is for a type alias template that has been substituted...
Definition: Type.h:6720
Represents a declaration of a type.
Definition: Decl.h:3370
const Type * getTypeForDecl() const
Definition: Decl.h:3395
The type-property cache.
Definition: Type.cpp:4501
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8510
bool isIncompleteArrayType() const
Definition: Type.h:8266
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isExtVectorBoolType() const
Definition: Type.h:8306
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isMemberDataPointerType() const
Definition: Type.h:8251
bool isBitIntType() const
Definition: Type.h:8424
bool isComplexIntegerType() const
Definition: Type.cpp:716
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
TypeClass getTypeClass() const
Definition: Type.h:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isRecordType() const
Definition: Type.h:8286
bool isUnionType() const
Definition: Type.cpp:704
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
QualType getUnderlyingType() const
Definition: Decl.h:3468
TypedefNameDecl * getDecl() const
Definition: Type.h:5740
Represents a C++ using-declaration.
Definition: DeclCXX.h:3530
Represents C++ using-directive.
Definition: DeclCXX.h:3033
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:3050
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3731
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3338
static bool hasVtableSlot(const CXXMethodDecl *MD)
Determine whether this function should be assigned a vtable slot.
ArrayRef< VTableComponent > vtable_components() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
const Expr * getInit() const
Definition: Decl.h:1319
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2674
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, BlockDecl > blockDecl
Matches block declarations.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
@ Result
The result type of a method or function.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
DynamicInitKind
Definition: GlobalDecl.h:32
@ Dtor_Deleting
Deleting dtor.
Definition: ABI.h:34
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86Pascal
Definition: Specifiers.h:284
@ CC_Swift
Definition: Specifiers.h:293
@ CC_IntelOclBicc
Definition: Specifiers.h:290
@ CC_OpenCLKernel
Definition: Specifiers.h:292
@ CC_PreserveMost
Definition: Specifiers.h:295
@ CC_Win64
Definition: Specifiers.h:285
@ CC_X86ThisCall
Definition: Specifiers.h:282
@ CC_AArch64VectorCall
Definition: Specifiers.h:297
@ CC_AAPCS
Definition: Specifiers.h:288
@ CC_PreserveNone
Definition: Specifiers.h:301
@ CC_C
Definition: Specifiers.h:279
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:299
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_SwiftAsync
Definition: Specifiers.h:294
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_RISCVVectorCall
Definition: Specifiers.h:302
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_SpirFunction
Definition: Specifiers.h:291
@ CC_AArch64SVEPCS
Definition: Specifiers.h:298
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ CC_PreserveAll
Definition: Specifiers.h:296
@ CC_X86FastCall
Definition: Specifiers.h:281
@ CC_AAPCS_VFP
Definition: Specifiers.h:289
@ Generic
not a target-specific vector type
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ CXXThis
Parameter for C++ 'this' argument.
@ ObjCSelf
Parameter for Objective-C 'self' argument.
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition: Version.cpp:96
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
@ AS_private
Definition: Specifiers.h:126
unsigned long uint64_t
long int64_t
unsigned int uint32_t
#define true
Definition: stdbool.h:25
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:5187
uint64_t Index
Method's index in the vftable.
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned MSVCFormatting
Use whitespace and punctuation like MSVC does.
unsigned SplitTemplateClosers
Whether nested templates must be closed like 'a<b<c> >' rather than 'a<b<c>>'.
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned AlwaysIncludeTypeForTemplateArgument
Whether to use type suffixes (eg: 1U) on integral non-type template parameters.
unsigned UsePreferredNames
Whether to use C++ template preferred_name attributes when printing templates.
unsigned UseEnumerators
Whether to print enumerator non-type template parameters with a matching enumerator name or via cast ...
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.
const PrintingCallbacks * Callbacks
Callbacks to use to allow the behavior of printing to be customized.
A this pointer adjustment.
Definition: Thunk.h:92
bool isAlignRequired()
Definition: ASTContext.h:167
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160