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::CreateEnumType(const EnumType *Ty) {
3496 const EnumDecl *ED = Ty->getDecl();
3497
3498 uint64_t Size = 0;
3499 uint32_t Align = 0;
3500 if (!ED->getTypeForDecl()->isIncompleteType()) {
3502 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3503 }
3504
3506
3507 bool isImportedFromModule =
3508 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3509
3510 // If this is just a forward declaration, construct an appropriately
3511 // marked node and just return it.
3512 if (isImportedFromModule || !ED->getDefinition()) {
3513 // Note that it is possible for enums to be created as part of
3514 // their own declcontext. In this case a FwdDecl will be created
3515 // twice. This doesn't cause a problem because both FwdDecls are
3516 // entered into the ReplaceMap: finalize() will replace the first
3517 // FwdDecl with the second and then replace the second with
3518 // complete type.
3519 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3520 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3521 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3522 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3523
3524 unsigned Line = getLineNumber(ED->getLocation());
3525 StringRef EDName = ED->getName();
3526 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3527 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3528 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3529
3530 ReplaceMap.emplace_back(
3531 std::piecewise_construct, std::make_tuple(Ty),
3532 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3533 return RetTy;
3534 }
3535
3536 return CreateTypeDefinition(Ty);
3537}
3538
3539llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3540 const EnumDecl *ED = Ty->getDecl();
3541 uint64_t Size = 0;
3542 uint32_t Align = 0;
3543 if (!ED->getTypeForDecl()->isIncompleteType()) {
3545 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3546 }
3547
3549
3551 ED = ED->getDefinition();
3552 assert(ED && "An enumeration definition is required");
3553 for (const auto *Enum : ED->enumerators()) {
3554 Enumerators.push_back(
3555 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3556 }
3557
3558 // Return a CompositeType for the enum itself.
3559 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3560
3561 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3562 unsigned Line = getLineNumber(ED->getLocation());
3563 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3564 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3565 return DBuilder.createEnumerationType(
3566 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3567 /*RunTimeLang=*/0, Identifier, ED->isScoped());
3568}
3569
3570llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3571 unsigned MType, SourceLocation LineLoc,
3572 StringRef Name, StringRef Value) {
3573 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3574 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3575}
3576
3577llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3578 SourceLocation LineLoc,
3579 SourceLocation FileLoc) {
3580 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3581 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3582 return DBuilder.createTempMacroFile(Parent, Line, FName);
3583}
3584
3586 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
3587 // Create a debug location from `TrapLocation` that adds an artificial inline
3588 // frame.
3590
3591 FuncName += "$";
3592 FuncName += Category;
3593 FuncName += "$";
3594 FuncName += FailureMsg;
3595
3596 llvm::DISubprogram *TrapSP =
3597 createInlinedTrapSubprogram(FuncName, TrapLocation->getFile());
3598 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
3599 /*Scope=*/TrapSP, /*InlinedAt=*/TrapLocation);
3600}
3601
3603 Qualifiers Quals;
3604 do {
3605 Qualifiers InnerQuals = T.getLocalQualifiers();
3606 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3607 // that is already there.
3608 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3609 Quals += InnerQuals;
3610 QualType LastT = T;
3611 switch (T->getTypeClass()) {
3612 default:
3613 return C.getQualifiedType(T.getTypePtr(), Quals);
3614 case Type::TemplateSpecialization: {
3615 const auto *Spec = cast<TemplateSpecializationType>(T);
3616 if (Spec->isTypeAlias())
3617 return C.getQualifiedType(T.getTypePtr(), Quals);
3618 T = Spec->desugar();
3619 break;
3620 }
3621 case Type::TypeOfExpr:
3622 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3623 break;
3624 case Type::TypeOf:
3625 T = cast<TypeOfType>(T)->getUnmodifiedType();
3626 break;
3627 case Type::Decltype:
3628 T = cast<DecltypeType>(T)->getUnderlyingType();
3629 break;
3630 case Type::UnaryTransform:
3631 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3632 break;
3633 case Type::Attributed:
3634 T = cast<AttributedType>(T)->getEquivalentType();
3635 break;
3636 case Type::BTFTagAttributed:
3637 T = cast<BTFTagAttributedType>(T)->getWrappedType();
3638 break;
3639 case Type::CountAttributed:
3640 T = cast<CountAttributedType>(T)->desugar();
3641 break;
3642 case Type::Elaborated:
3643 T = cast<ElaboratedType>(T)->getNamedType();
3644 break;
3645 case Type::Using:
3646 T = cast<UsingType>(T)->getUnderlyingType();
3647 break;
3648 case Type::Paren:
3649 T = cast<ParenType>(T)->getInnerType();
3650 break;
3651 case Type::MacroQualified:
3652 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3653 break;
3654 case Type::SubstTemplateTypeParm:
3655 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3656 break;
3657 case Type::Auto:
3658 case Type::DeducedTemplateSpecialization: {
3659 QualType DT = cast<DeducedType>(T)->getDeducedType();
3660 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3661 T = DT;
3662 break;
3663 }
3664 case Type::PackIndexing: {
3665 T = cast<PackIndexingType>(T)->getSelectedType();
3666 break;
3667 }
3668 case Type::Adjusted:
3669 case Type::Decayed:
3670 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3671 T = cast<AdjustedType>(T)->getAdjustedType();
3672 break;
3673 }
3674
3675 assert(T != LastT && "Type unwrapping failed to unwrap!");
3676 (void)LastT;
3677 } while (true);
3678}
3679
3680llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3681 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3682 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3683 if (It != TypeCache.end()) {
3684 // Verify that the debug info still exists.
3685 if (llvm::Metadata *V = It->second)
3686 return cast<llvm::DIType>(V);
3687 }
3688
3689 return nullptr;
3690}
3691
3695}
3696
3698 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
3699 D.isDynamicClass())
3700 return;
3701
3703 // In case this type has no member function definitions being emitted, ensure
3704 // it is retained
3705 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3706}
3707
3708llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3709 if (Ty.isNull())
3710 return nullptr;
3711
3712 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3713 std::string Name;
3714 llvm::raw_string_ostream OS(Name);
3715 Ty.print(OS, getPrintingPolicy());
3716 return Name;
3717 });
3718
3719 // Unwrap the type as needed for debug information.
3720 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3721
3722 if (auto *T = getTypeOrNull(Ty))
3723 return T;
3724
3725 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3726 void *TyPtr = Ty.getAsOpaquePtr();
3727
3728 // And update the type cache.
3729 TypeCache[TyPtr].reset(Res);
3730
3731 return Res;
3732}
3733
3734llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3735 // A forward declaration inside a module header does not belong to the module.
3736 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3737 return nullptr;
3738 if (DebugTypeExtRefs && D->isFromASTFile()) {
3739 // Record a reference to an imported clang module or precompiled header.
3740 auto *Reader = CGM.getContext().getExternalSource();
3741 auto Idx = D->getOwningModuleID();
3742 auto Info = Reader->getSourceDescriptor(Idx);
3743 if (Info)
3744 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3745 } else if (ClangModuleMap) {
3746 // We are building a clang module or a precompiled header.
3747 //
3748 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3749 // and it wouldn't be necessary to specify the parent scope
3750 // because the type is already unique by definition (it would look
3751 // like the output of -fno-standalone-debug). On the other hand,
3752 // the parent scope helps a consumer to quickly locate the object
3753 // file where the type's definition is located, so it might be
3754 // best to make this behavior a command line or debugger tuning
3755 // option.
3756 if (Module *M = D->getOwningModule()) {
3757 // This is a (sub-)module.
3758 auto Info = ASTSourceDescriptor(*M);
3759 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3760 } else {
3761 // This the precompiled header being built.
3762 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3763 }
3764 }
3765
3766 return nullptr;
3767}
3768
3769llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3770 // Handle qualifiers, which recursively handles what they refer to.
3771 if (Ty.hasLocalQualifiers())
3772 return CreateQualifiedType(Ty, Unit);
3773
3774 // Work out details of type.
3775 switch (Ty->getTypeClass()) {
3776#define TYPE(Class, Base)
3777#define ABSTRACT_TYPE(Class, Base)
3778#define NON_CANONICAL_TYPE(Class, Base)
3779#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3780#include "clang/AST/TypeNodes.inc"
3781 llvm_unreachable("Dependent types cannot show up in debug information");
3782
3783 case Type::ExtVector:
3784 case Type::Vector:
3785 return CreateType(cast<VectorType>(Ty), Unit);
3786 case Type::ConstantMatrix:
3787 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3788 case Type::ObjCObjectPointer:
3789 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3790 case Type::ObjCObject:
3791 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3792 case Type::ObjCTypeParam:
3793 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3794 case Type::ObjCInterface:
3795 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3796 case Type::Builtin:
3797 return CreateType(cast<BuiltinType>(Ty));
3798 case Type::Complex:
3799 return CreateType(cast<ComplexType>(Ty));
3800 case Type::Pointer:
3801 return CreateType(cast<PointerType>(Ty), Unit);
3802 case Type::BlockPointer:
3803 return CreateType(cast<BlockPointerType>(Ty), Unit);
3804 case Type::Typedef:
3805 return CreateType(cast<TypedefType>(Ty), Unit);
3806 case Type::Record:
3807 return CreateType(cast<RecordType>(Ty));
3808 case Type::Enum:
3809 return CreateEnumType(cast<EnumType>(Ty));
3810 case Type::FunctionProto:
3811 case Type::FunctionNoProto:
3812 return CreateType(cast<FunctionType>(Ty), Unit);
3813 case Type::ConstantArray:
3814 case Type::VariableArray:
3815 case Type::IncompleteArray:
3816 case Type::ArrayParameter:
3817 return CreateType(cast<ArrayType>(Ty), Unit);
3818
3819 case Type::LValueReference:
3820 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3821 case Type::RValueReference:
3822 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3823
3824 case Type::MemberPointer:
3825 return CreateType(cast<MemberPointerType>(Ty), Unit);
3826
3827 case Type::Atomic:
3828 return CreateType(cast<AtomicType>(Ty), Unit);
3829
3830 case Type::BitInt:
3831 return CreateType(cast<BitIntType>(Ty));
3832 case Type::Pipe:
3833 return CreateType(cast<PipeType>(Ty), Unit);
3834
3835 case Type::TemplateSpecialization:
3836 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3837
3838 case Type::CountAttributed:
3839 case Type::Auto:
3840 case Type::Attributed:
3841 case Type::BTFTagAttributed:
3842 case Type::HLSLAttributedResource:
3843 case Type::Adjusted:
3844 case Type::Decayed:
3845 case Type::DeducedTemplateSpecialization:
3846 case Type::Elaborated:
3847 case Type::Using:
3848 case Type::Paren:
3849 case Type::MacroQualified:
3850 case Type::SubstTemplateTypeParm:
3851 case Type::TypeOfExpr:
3852 case Type::TypeOf:
3853 case Type::Decltype:
3854 case Type::PackIndexing:
3855 case Type::UnaryTransform:
3856 break;
3857 }
3858
3859 llvm_unreachable("type should have been unwrapped!");
3860}
3861
3862llvm::DICompositeType *
3863CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3864 QualType QTy(Ty, 0);
3865
3866 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3867
3868 // We may have cached a forward decl when we could have created
3869 // a non-forward decl. Go ahead and create a non-forward decl
3870 // now.
3871 if (T && !T->isForwardDecl())
3872 return T;
3873
3874 // Otherwise create the type.
3875 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3876
3877 // Propagate members from the declaration to the definition
3878 // CreateType(const RecordType*) will overwrite this with the members in the
3879 // correct order if the full type is needed.
3880 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3881
3882 // And update the type cache.
3883 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3884 return Res;
3885}
3886
3887// TODO: Currently used for context chains when limiting debug info.
3888llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3889 RecordDecl *RD = Ty->getDecl();
3890
3891 // Get overall information about the record type for the debug info.
3892 StringRef RDName = getClassName(RD);
3893 const SourceLocation Loc = RD->getLocation();
3894 llvm::DIFile *DefUnit = nullptr;
3895 unsigned Line = 0;
3896 if (Loc.isValid()) {
3897 DefUnit = getOrCreateFile(Loc);
3898 Line = getLineNumber(Loc);
3899 }
3900
3901 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3902
3903 // If we ended up creating the type during the context chain construction,
3904 // just return that.
3905 auto *T = cast_or_null<llvm::DICompositeType>(
3906 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3907 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3908 return T;
3909
3910 // If this is just a forward or incomplete declaration, construct an
3911 // appropriately marked node and just return it.
3912 const RecordDecl *D = RD->getDefinition();
3913 if (!D || !D->isCompleteDefinition())
3914 return getOrCreateRecordFwdDecl(Ty, RDContext);
3915
3916 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3917 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3918 // struct or struct member, where it only increases alignment unless 'packed'
3919 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3920 // to be used.
3921 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3922
3924
3925 // Explicitly record the calling convention and export symbols for C++
3926 // records.
3927 auto Flags = llvm::DINode::FlagZero;
3928 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3930 Flags |= llvm::DINode::FlagTypePassByReference;
3931 else
3932 Flags |= llvm::DINode::FlagTypePassByValue;
3933
3934 // Record if a C++ record is non-trivial type.
3935 if (!CXXRD->isTrivial())
3936 Flags |= llvm::DINode::FlagNonTrivial;
3937
3938 // Record exports it symbols to the containing structure.
3939 if (CXXRD->isAnonymousStructOrUnion())
3940 Flags |= llvm::DINode::FlagExportSymbols;
3941
3942 Flags |= getAccessFlag(CXXRD->getAccess(),
3943 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3944 }
3945
3946 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3947 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3948 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3949 Flags, Identifier, Annotations);
3950
3951 // Elements of composite types usually have back to the type, creating
3952 // uniquing cycles. Distinct nodes are more efficient.
3953 switch (RealDecl->getTag()) {
3954 default:
3955 llvm_unreachable("invalid composite type tag");
3956
3957 case llvm::dwarf::DW_TAG_array_type:
3958 case llvm::dwarf::DW_TAG_enumeration_type:
3959 // Array elements and most enumeration elements don't have back references,
3960 // so they don't tend to be involved in uniquing cycles and there is some
3961 // chance of merging them when linking together two modules. Only make
3962 // them distinct if they are ODR-uniqued.
3963 if (Identifier.empty())
3964 break;
3965 [[fallthrough]];
3966
3967 case llvm::dwarf::DW_TAG_structure_type:
3968 case llvm::dwarf::DW_TAG_union_type:
3969 case llvm::dwarf::DW_TAG_class_type:
3970 // Immediately resolve to a distinct node.
3971 RealDecl =
3972 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3973 break;
3974 }
3975
3976 RegionMap[Ty->getDecl()].reset(RealDecl);
3977 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3978
3979 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3980 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3981 CollectCXXTemplateParams(TSpecial, DefUnit));
3982 return RealDecl;
3983}
3984
3985void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3986 llvm::DICompositeType *RealDecl) {
3987 // A class's primary base or the class itself contains the vtable.
3988 llvm::DIType *ContainingType = nullptr;
3989 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3990 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3991 // Seek non-virtual primary base root.
3992 while (true) {
3993 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3994 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3995 if (PBT && !BRL.isPrimaryBaseVirtual())
3996 PBase = PBT;
3997 else
3998 break;
3999 }
4000 ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
4001 getOrCreateFile(RD->getLocation()));
4002 } else if (RD->isDynamicClass())
4003 ContainingType = RealDecl;
4004
4005 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4006}
4007
4008llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4009 StringRef Name, uint64_t *Offset) {
4010 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4011 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4012 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4013 llvm::DIType *Ty =
4014 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4015 *Offset, llvm::DINode::FlagZero, FieldTy);
4016 *Offset += FieldSize;
4017 return Ty;
4018}
4019
4020void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4021 StringRef &Name,
4022 StringRef &LinkageName,
4023 llvm::DIScope *&FDContext,
4024 llvm::DINodeArray &TParamsArray,
4025 llvm::DINode::DIFlags &Flags) {
4026 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4027 Name = getFunctionName(FD);
4028 // Use mangled name as linkage name for C/C++ functions.
4029 if (FD->getType()->getAs<FunctionProtoType>())
4030 LinkageName = CGM.getMangledName(GD);
4031 if (FD->hasPrototype())
4032 Flags |= llvm::DINode::FlagPrototyped;
4033 // No need to replicate the linkage name if it isn't different from the
4034 // subprogram name, no need to have it at all unless coverage is enabled or
4035 // debug is set to more than just line tables or extra debug info is needed.
4036 if (LinkageName == Name ||
4037 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4038 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4039 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4040 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4041 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4042 LinkageName = StringRef();
4043
4044 // Emit the function scope in line tables only mode (if CodeView) to
4045 // differentiate between function names.
4046 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4047 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4048 CGM.getCodeGenOpts().EmitCodeView)) {
4049 if (const NamespaceDecl *NSDecl =
4050 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4051 FDContext = getOrCreateNamespace(NSDecl);
4052 else if (const RecordDecl *RDecl =
4053 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4054 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4055 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4056 }
4057 }
4058 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4059 // Check if it is a noreturn-marked function
4060 if (FD->isNoReturn())
4061 Flags |= llvm::DINode::FlagNoReturn;
4062 // Collect template parameters.
4063 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4064 }
4065}
4066
4067void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4068 unsigned &LineNo, QualType &T,
4069 StringRef &Name, StringRef &LinkageName,
4070 llvm::MDTuple *&TemplateParameters,
4071 llvm::DIScope *&VDContext) {
4072 Unit = getOrCreateFile(VD->getLocation());
4073 LineNo = getLineNumber(VD->getLocation());
4074
4075 setLocation(VD->getLocation());
4076
4077 T = VD->getType();
4078 if (T->isIncompleteArrayType()) {
4079 // CodeGen turns int[] into int[1] so we'll do the same here.
4080 llvm::APInt ConstVal(32, 1);
4082
4083 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4085 }
4086
4087 Name = VD->getName();
4088 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4089 !isa<ObjCMethodDecl>(VD->getDeclContext()))
4090 LinkageName = CGM.getMangledName(VD);
4091 if (LinkageName == Name)
4092 LinkageName = StringRef();
4093
4094 if (isa<VarTemplateSpecializationDecl>(VD)) {
4095 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4096 TemplateParameters = parameterNodes.get();
4097 } else {
4098 TemplateParameters = nullptr;
4099 }
4100
4101 // Since we emit declarations (DW_AT_members) for static members, place the
4102 // definition of those static members in the namespace they were declared in
4103 // in the source code (the lexical decl context).
4104 // FIXME: Generalize this for even non-member global variables where the
4105 // declaration and definition may have different lexical decl contexts, once
4106 // we have support for emitting declarations of (non-member) global variables.
4107 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4108 : VD->getDeclContext();
4109 // When a record type contains an in-line initialization of a static data
4110 // member, and the record type is marked as __declspec(dllexport), an implicit
4111 // definition of the member will be created in the record context. DWARF
4112 // doesn't seem to have a nice way to describe this in a form that consumers
4113 // are likely to understand, so fake the "normal" situation of a definition
4114 // outside the class by putting it in the global scope.
4115 if (DC->isRecord())
4117
4118 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4119 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4120}
4121
4122llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4123 bool Stub) {
4124 llvm::DINodeArray TParamsArray;
4125 StringRef Name, LinkageName;
4126 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4127 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4129 llvm::DIFile *Unit = getOrCreateFile(Loc);
4130 llvm::DIScope *DContext = Unit;
4131 unsigned Line = getLineNumber(Loc);
4132 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4133 Flags);
4134 auto *FD = cast<FunctionDecl>(GD.getDecl());
4135
4136 // Build function type.
4138 for (const ParmVarDecl *Parm : FD->parameters())
4139 ArgTypes.push_back(Parm->getType());
4140
4141 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4142 QualType FnType = CGM.getContext().getFunctionType(
4143 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4144 if (!FD->isExternallyVisible())
4145 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4146 if (CGM.getLangOpts().Optimize)
4147 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4148
4149 if (Stub) {
4150 Flags |= getCallSiteRelatedAttrs();
4151 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4152 return DBuilder.createFunction(
4153 DContext, Name, LinkageName, Unit, Line,
4154 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4155 TParamsArray.get(), getFunctionDeclaration(FD));
4156 }
4157
4158 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4159 DContext, Name, LinkageName, Unit, Line,
4160 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4161 TParamsArray.get(), getFunctionDeclaration(FD));
4162 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4163 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4164 std::make_tuple(CanonDecl),
4165 std::make_tuple(SP));
4166 return SP;
4167}
4168
4169llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4170 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4171}
4172
4173llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4174 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4175}
4176
4177llvm::DIGlobalVariable *
4178CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4179 QualType T;
4180 StringRef Name, LinkageName;
4182 llvm::DIFile *Unit = getOrCreateFile(Loc);
4183 llvm::DIScope *DContext = Unit;
4184 unsigned Line = getLineNumber(Loc);
4185 llvm::MDTuple *TemplateParameters = nullptr;
4186
4187 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4188 DContext);
4189 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4190 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4191 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4192 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4193 FwdDeclReplaceMap.emplace_back(
4194 std::piecewise_construct,
4195 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4196 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4197 return GV;
4198}
4199
4200llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4201 // We only need a declaration (not a definition) of the type - so use whatever
4202 // we would otherwise do to get a type for a pointee. (forward declarations in
4203 // limited debug info, full definitions (if the type definition is available)
4204 // in unlimited debug info)
4205 if (const auto *TD = dyn_cast<TypeDecl>(D))
4206 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
4207 getOrCreateFile(TD->getLocation()));
4208 auto I = DeclCache.find(D->getCanonicalDecl());
4209
4210 if (I != DeclCache.end()) {
4211 auto N = I->second;
4212 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4213 return GVE->getVariable();
4214 return cast<llvm::DINode>(N);
4215 }
4216
4217 // Search imported declaration cache if it is already defined
4218 // as imported declaration.
4219 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4220
4221 if (IE != ImportedDeclCache.end()) {
4222 auto N = IE->second;
4223 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4224 return cast<llvm::DINode>(GVE);
4225 return dyn_cast_or_null<llvm::DINode>(N);
4226 }
4227
4228 // No definition for now. Emit a forward definition that might be
4229 // merged with a potential upcoming definition.
4230 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4231 return getFunctionForwardDeclaration(FD);
4232 else if (const auto *VD = dyn_cast<VarDecl>(D))
4233 return getGlobalVariableForwardDeclaration(VD);
4234
4235 return nullptr;
4236}
4237
4238llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4239 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4240 return nullptr;
4241
4242 const auto *FD = dyn_cast<FunctionDecl>(D);
4243 if (!FD)
4244 return nullptr;
4245
4246 // Setup context.
4247 auto *S = getDeclContextDescriptor(D);
4248
4249 auto MI = SPCache.find(FD->getCanonicalDecl());
4250 if (MI == SPCache.end()) {
4251 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4252 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4253 cast<llvm::DICompositeType>(S));
4254 }
4255 }
4256 if (MI != SPCache.end()) {
4257 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4258 if (SP && !SP->isDefinition())
4259 return SP;
4260 }
4261
4262 for (auto *NextFD : FD->redecls()) {
4263 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4264 if (MI != SPCache.end()) {
4265 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4266 if (SP && !SP->isDefinition())
4267 return SP;
4268 }
4269 }
4270 return nullptr;
4271}
4272
4273llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4274 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4275 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4276 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4277 return nullptr;
4278
4279 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4280 if (!OMD)
4281 return nullptr;
4282
4283 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4284 return nullptr;
4285
4286 if (OMD->isDirectMethod())
4287 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4288
4289 // Starting with DWARF V5 method declarations are emitted as children of
4290 // the interface type.
4291 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4292 if (!ID)
4293 ID = OMD->getClassInterface();
4294 if (!ID)
4295 return nullptr;
4296 QualType QTy(ID->getTypeForDecl(), 0);
4297 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4298 if (It == TypeCache.end())
4299 return nullptr;
4300 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4301 llvm::DISubprogram *FD = DBuilder.createFunction(
4302 InterfaceType, getObjCMethodName(OMD), StringRef(),
4303 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4304 DBuilder.finalizeSubprogram(FD);
4305 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4306 return FD;
4307}
4308
4309// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4310// implicit parameter "this".
4311llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4312 QualType FnType,
4313 llvm::DIFile *F) {
4314 // In CodeView, we emit the function types in line tables only because the
4315 // only way to distinguish between functions is by display name and type.
4316 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4317 !CGM.getCodeGenOpts().EmitCodeView))
4318 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4319 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4320 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4321
4322 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4323 return getOrCreateMethodType(Method, F);
4324
4325 const auto *FTy = FnType->getAs<FunctionType>();
4326 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4327
4328 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4329 // Add "self" and "_cmd"
4331
4332 // First element is always return type. For 'void' functions it is NULL.
4333 QualType ResultTy = OMethod->getReturnType();
4334
4335 // Replace the instancetype keyword with the actual type.
4336 if (ResultTy == CGM.getContext().getObjCInstanceType())
4337 ResultTy = CGM.getContext().getPointerType(
4338 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4339
4340 Elts.push_back(getOrCreateType(ResultTy, F));
4341 // "self" pointer is always first argument.
4342 QualType SelfDeclTy;
4343 if (auto *SelfDecl = OMethod->getSelfDecl())
4344 SelfDeclTy = SelfDecl->getType();
4345 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4346 if (FPT->getNumParams() > 1)
4347 SelfDeclTy = FPT->getParamType(0);
4348 if (!SelfDeclTy.isNull())
4349 Elts.push_back(
4350 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4351 // "_cmd" pointer is always second argument.
4352 Elts.push_back(DBuilder.createArtificialType(
4353 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4354 // Get rest of the arguments.
4355 for (const auto *PI : OMethod->parameters())
4356 Elts.push_back(getOrCreateType(PI->getType(), F));
4357 // Variadic methods need a special marker at the end of the type list.
4358 if (OMethod->isVariadic())
4359 Elts.push_back(DBuilder.createUnspecifiedParameter());
4360
4361 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4362 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4363 getDwarfCC(CC));
4364 }
4365
4366 // Handle variadic function types; they need an additional
4367 // unspecified parameter.
4368 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4369 if (FD->isVariadic()) {
4371 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4372 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4373 for (QualType ParamType : FPT->param_types())
4374 EltTys.push_back(getOrCreateType(ParamType, F));
4375 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4376 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4377 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4378 getDwarfCC(CC));
4379 }
4380
4381 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4382}
4383
4388 if (FD)
4389 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4390 CC = SrcFnTy->getCallConv();
4392 for (const VarDecl *VD : Args)
4393 ArgTypes.push_back(VD->getType());
4394 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4396}
4397
4399 SourceLocation ScopeLoc, QualType FnType,
4400 llvm::Function *Fn, bool CurFuncIsThunk) {
4401 StringRef Name;
4402 StringRef LinkageName;
4403
4404 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4405
4406 const Decl *D = GD.getDecl();
4407 bool HasDecl = (D != nullptr);
4408
4409 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4410 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4411 llvm::DIFile *Unit = getOrCreateFile(Loc);
4412 llvm::DIScope *FDContext = Unit;
4413 llvm::DINodeArray TParamsArray;
4414 if (!HasDecl) {
4415 // Use llvm function name.
4416 LinkageName = Fn->getName();
4417 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4418 // If there is a subprogram for this function available then use it.
4419 auto FI = SPCache.find(FD->getCanonicalDecl());
4420 if (FI != SPCache.end()) {
4421 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4422 if (SP && SP->isDefinition()) {
4423 LexicalBlockStack.emplace_back(SP);
4424 RegionMap[D].reset(SP);
4425 return;
4426 }
4427 }
4428 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4429 TParamsArray, Flags);
4430 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4431 Name = getObjCMethodName(OMD);
4432 Flags |= llvm::DINode::FlagPrototyped;
4433 } else if (isa<VarDecl>(D) &&
4435 // This is a global initializer or atexit destructor for a global variable.
4436 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4437 Fn);
4438 } else {
4439 Name = Fn->getName();
4440
4441 if (isa<BlockDecl>(D))
4442 LinkageName = Name;
4443
4444 Flags |= llvm::DINode::FlagPrototyped;
4445 }
4446 if (Name.starts_with("\01"))
4447 Name = Name.substr(1);
4448
4449 assert((!D || !isa<VarDecl>(D) ||
4451 "Unexpected DynamicInitKind !");
4452
4453 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4454 isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4455 Flags |= llvm::DINode::FlagArtificial;
4456 // Artificial functions should not silently reuse CurLoc.
4457 CurLoc = SourceLocation();
4458 }
4459
4460 if (CurFuncIsThunk)
4461 Flags |= llvm::DINode::FlagThunk;
4462
4463 if (Fn->hasLocalLinkage())
4464 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4465 if (CGM.getLangOpts().Optimize)
4466 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4467
4468 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4469 llvm::DISubprogram::DISPFlags SPFlagsForDef =
4470 SPFlags | llvm::DISubprogram::SPFlagDefinition;
4471
4472 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4473 unsigned ScopeLine = getLineNumber(ScopeLoc);
4474 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4475 llvm::DISubprogram *Decl = nullptr;
4476 llvm::DINodeArray Annotations = nullptr;
4477 if (D) {
4478 Decl = isa<ObjCMethodDecl>(D)
4479 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4480 : getFunctionDeclaration(D);
4481 Annotations = CollectBTFDeclTagAnnotations(D);
4482 }
4483
4484 // FIXME: The function declaration we're constructing here is mostly reusing
4485 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4486 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4487 // all subprograms instead of the actual context since subprogram definitions
4488 // are emitted as CU level entities by the backend.
4489 llvm::DISubprogram *SP = DBuilder.createFunction(
4490 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4491 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4492 Annotations);
4493 Fn->setSubprogram(SP);
4494 // We might get here with a VarDecl in the case we're generating
4495 // code for the initialization of globals. Do not record these decls
4496 // as they will overwrite the actual VarDecl Decl in the cache.
4497 if (HasDecl && isa<FunctionDecl>(D))
4498 DeclCache[D->getCanonicalDecl()].reset(SP);
4499
4500 // Push the function onto the lexical block stack.
4501 LexicalBlockStack.emplace_back(SP);
4502
4503 if (HasDecl)
4504 RegionMap[D].reset(SP);
4505}
4506
4508 QualType FnType, llvm::Function *Fn) {
4509 StringRef Name;
4510 StringRef LinkageName;
4511
4512 const Decl *D = GD.getDecl();
4513 if (!D)
4514 return;
4515
4516 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4517 return GetName(D, true);
4518 });
4519
4520 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4521 llvm::DIFile *Unit = getOrCreateFile(Loc);
4522 bool IsDeclForCallSite = Fn ? true : false;
4523 llvm::DIScope *FDContext =
4524 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4525 llvm::DINodeArray TParamsArray;
4526 if (isa<FunctionDecl>(D)) {
4527 // If there is a DISubprogram for this function available then use it.
4528 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4529 TParamsArray, Flags);
4530 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4531 Name = getObjCMethodName(OMD);
4532 Flags |= llvm::DINode::FlagPrototyped;
4533 } else {
4534 llvm_unreachable("not a function or ObjC method");
4535 }
4536 if (!Name.empty() && Name[0] == '\01')
4537 Name = Name.substr(1);
4538
4539 if (D->isImplicit()) {
4540 Flags |= llvm::DINode::FlagArtificial;
4541 // Artificial functions without a location should not silently reuse CurLoc.
4542 if (Loc.isInvalid())
4543 CurLoc = SourceLocation();
4544 }
4545 unsigned LineNo = getLineNumber(Loc);
4546 unsigned ScopeLine = 0;
4547 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4548 if (CGM.getLangOpts().Optimize)
4549 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4550
4551 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4552 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4553 llvm::DISubprogram *SP = DBuilder.createFunction(
4554 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4555 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
4556
4557 // Preserve btf_decl_tag attributes for parameters of extern functions
4558 // for BPF target. The parameters created in this loop are attached as
4559 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4560 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4561 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4562 llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4563 unsigned ArgNo = 1;
4564 for (ParmVarDecl *PD : FD->parameters()) {
4565 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4566 DBuilder.createParameterVariable(
4567 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4568 llvm::DINode::FlagZero, ParamAnnotations);
4569 ++ArgNo;
4570 }
4571 }
4572 }
4573
4574 if (IsDeclForCallSite)
4575 Fn->setSubprogram(SP);
4576
4577 DBuilder.finalizeSubprogram(SP);
4578}
4579
4580void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4581 QualType CalleeType,
4582 const FunctionDecl *CalleeDecl) {
4583 if (!CallOrInvoke)
4584 return;
4585 auto *Func = CallOrInvoke->getCalledFunction();
4586 if (!Func)
4587 return;
4588 if (Func->getSubprogram())
4589 return;
4590
4591 // Do not emit a declaration subprogram for a function with nodebug
4592 // attribute, or if call site info isn't required.
4593 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4594 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4595 return;
4596
4597 // If there is no DISubprogram attached to the function being called,
4598 // create the one describing the function in order to have complete
4599 // call site debug info.
4600 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4601 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4602}
4603
4605 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4606 // If there is a subprogram for this function available then use it.
4607 auto FI = SPCache.find(FD->getCanonicalDecl());
4608 llvm::DISubprogram *SP = nullptr;
4609 if (FI != SPCache.end())
4610 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4611 if (!SP || !SP->isDefinition())
4612 SP = getFunctionStub(GD);
4613 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4614 LexicalBlockStack.emplace_back(SP);
4615 setInlinedAt(Builder.getCurrentDebugLocation());
4616 EmitLocation(Builder, FD->getLocation());
4617}
4618
4620 assert(CurInlinedAt && "unbalanced inline scope stack");
4621 EmitFunctionEnd(Builder, nullptr);
4622 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4623}
4624
4626 // Update our current location
4628
4629 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4630 return;
4631
4632 llvm::MDNode *Scope = LexicalBlockStack.back();
4633 Builder.SetCurrentDebugLocation(
4634 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4635 getColumnNumber(CurLoc), Scope, CurInlinedAt));
4636}
4637
4638void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4639 llvm::MDNode *Back = nullptr;
4640 if (!LexicalBlockStack.empty())
4641 Back = LexicalBlockStack.back().get();
4642 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4643 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4644 getColumnNumber(CurLoc)));
4645}
4646
4647void CGDebugInfo::AppendAddressSpaceXDeref(
4648 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4649 std::optional<unsigned> DWARFAddressSpace =
4650 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4651 if (!DWARFAddressSpace)
4652 return;
4653
4654 Expr.push_back(llvm::dwarf::DW_OP_constu);
4655 Expr.push_back(*DWARFAddressSpace);
4656 Expr.push_back(llvm::dwarf::DW_OP_swap);
4657 Expr.push_back(llvm::dwarf::DW_OP_xderef);
4658}
4659
4662 // Set our current location.
4664
4665 // Emit a line table change for the current location inside the new scope.
4666 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4667 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4668 LexicalBlockStack.back(), CurInlinedAt));
4669
4670 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4671 return;
4672
4673 // Create a new lexical block and push it on the stack.
4674 CreateLexicalBlock(Loc);
4675}
4676
4679 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4680
4681 // Provide an entry in the line table for the end of the block.
4682 EmitLocation(Builder, Loc);
4683
4684 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4685 return;
4686
4687 LexicalBlockStack.pop_back();
4688}
4689
4690void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4691 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4692 unsigned RCount = FnBeginRegionCount.back();
4693 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4694
4695 // Pop all regions for this function.
4696 while (LexicalBlockStack.size() != RCount) {
4697 // Provide an entry in the line table for the end of the block.
4698 EmitLocation(Builder, CurLoc);
4699 LexicalBlockStack.pop_back();
4700 }
4701 FnBeginRegionCount.pop_back();
4702
4703 if (Fn && Fn->getSubprogram())
4704 DBuilder.finalizeSubprogram(Fn->getSubprogram());
4705}
4706
4707CGDebugInfo::BlockByRefType
4708CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4709 uint64_t *XOffset) {
4711 QualType FType;
4712 uint64_t FieldSize, FieldOffset;
4713 uint32_t FieldAlign;
4714
4715 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4716 QualType Type = VD->getType();
4717
4718 FieldOffset = 0;
4719 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4720 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4721 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4722 FType = CGM.getContext().IntTy;
4723 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4724 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4725
4726 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4727 if (HasCopyAndDispose) {
4728 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4729 EltTys.push_back(
4730 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4731 EltTys.push_back(
4732 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4733 }
4734 bool HasByrefExtendedLayout;
4735 Qualifiers::ObjCLifetime Lifetime;
4736 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4737 HasByrefExtendedLayout) &&
4738 HasByrefExtendedLayout) {
4739 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4740 EltTys.push_back(
4741 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4742 }
4743
4744 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4745 if (Align > CGM.getContext().toCharUnitsFromBits(
4747 CharUnits FieldOffsetInBytes =
4748 CGM.getContext().toCharUnitsFromBits(FieldOffset);
4749 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4750 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4751
4752 if (NumPaddingBytes.isPositive()) {
4753 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4754 FType = CGM.getContext().getConstantArrayType(
4755 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
4756 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4757 }
4758 }
4759
4760 FType = Type;
4761 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4762 FieldSize = CGM.getContext().getTypeSize(FType);
4763 FieldAlign = CGM.getContext().toBits(Align);
4764
4765 *XOffset = FieldOffset;
4766 llvm::DIType *FieldTy = DBuilder.createMemberType(
4767 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4768 llvm::DINode::FlagZero, WrappedTy);
4769 EltTys.push_back(FieldTy);
4770 FieldOffset += FieldSize;
4771
4772 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4773 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4774 llvm::DINode::FlagZero, nullptr, Elements),
4775 WrappedTy};
4776}
4777
4778llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4779 llvm::Value *Storage,
4780 std::optional<unsigned> ArgNo,
4781 CGBuilderTy &Builder,
4782 const bool UsePointerValue) {
4783 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4784 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4785 if (VD->hasAttr<NoDebugAttr>())
4786 return nullptr;
4787
4788 const bool VarIsArtificial = IsArtificial(VD);
4789
4790 llvm::DIFile *Unit = nullptr;
4791 if (!VarIsArtificial)
4792 Unit = getOrCreateFile(VD->getLocation());
4793 llvm::DIType *Ty;
4794 uint64_t XOffset = 0;
4795 if (VD->hasAttr<BlocksAttr>())
4796 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4797 else
4798 Ty = getOrCreateType(VD->getType(), Unit);
4799
4800 // If there is no debug info for this type then do not emit debug info
4801 // for this variable.
4802 if (!Ty)
4803 return nullptr;
4804
4805 // Get location information.
4806 unsigned Line = 0;
4807 unsigned Column = 0;
4808 if (!VarIsArtificial) {
4809 Line = getLineNumber(VD->getLocation());
4810 Column = getColumnNumber(VD->getLocation());
4811 }
4813 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4814 if (VarIsArtificial)
4815 Flags |= llvm::DINode::FlagArtificial;
4816
4817 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4818
4819 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
4820 AppendAddressSpaceXDeref(AddressSpace, Expr);
4821
4822 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4823 // object pointer flag.
4824 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4825 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
4826 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
4827 Flags |= llvm::DINode::FlagObjectPointer;
4828 }
4829
4830 // Note: Older versions of clang used to emit byval references with an extra
4831 // DW_OP_deref, because they referenced the IR arg directly instead of
4832 // referencing an alloca. Newer versions of LLVM don't treat allocas
4833 // differently from other function arguments when used in a dbg.declare.
4834 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4835 StringRef Name = VD->getName();
4836 if (!Name.empty()) {
4837 // __block vars are stored on the heap if they are captured by a block that
4838 // can escape the local scope.
4839 if (VD->isEscapingByref()) {
4840 // Here, we need an offset *into* the alloca.
4842 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4843 // offset of __forwarding field
4844 offset = CGM.getContext().toCharUnitsFromBits(
4846 Expr.push_back(offset.getQuantity());
4847 Expr.push_back(llvm::dwarf::DW_OP_deref);
4848 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4849 // offset of x field
4850 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4851 Expr.push_back(offset.getQuantity());
4852 }
4853 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4854 // If VD is an anonymous union then Storage represents value for
4855 // all union fields.
4856 const RecordDecl *RD = RT->getDecl();
4857 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4858 // GDB has trouble finding local variables in anonymous unions, so we emit
4859 // artificial local variables for each of the members.
4860 //
4861 // FIXME: Remove this code as soon as GDB supports this.
4862 // The debug info verifier in LLVM operates based on the assumption that a
4863 // variable has the same size as its storage and we had to disable the
4864 // check for artificial variables.
4865 for (const auto *Field : RD->fields()) {
4866 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4867 StringRef FieldName = Field->getName();
4868
4869 // Ignore unnamed fields. Do not ignore unnamed records.
4870 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4871 continue;
4872
4873 // Use VarDecl's Tag, Scope and Line number.
4874 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4875 auto *D = DBuilder.createAutoVariable(
4876 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4877 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4878
4879 // Insert an llvm.dbg.declare into the current block.
4880 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4881 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4882 Column, Scope,
4883 CurInlinedAt),
4884 Builder.GetInsertBlock());
4885 }
4886 }
4887 }
4888
4889 // Clang stores the sret pointer provided by the caller in a static alloca.
4890 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4891 // the address of the variable.
4892 if (UsePointerValue) {
4893 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4894 "Debug info already contains DW_OP_deref.");
4895 Expr.push_back(llvm::dwarf::DW_OP_deref);
4896 }
4897
4898 // Create the descriptor for the variable.
4899 llvm::DILocalVariable *D = nullptr;
4900 if (ArgNo) {
4901 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4902 D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4903 CGM.getLangOpts().Optimize, Flags,
4904 Annotations);
4905 } else {
4906 // For normal local variable, we will try to find out whether 'VD' is the
4907 // copy parameter of coroutine.
4908 // If yes, we are going to use DIVariable of the origin parameter instead
4909 // of creating the new one.
4910 // If no, it might be a normal alloc, we just create a new one for it.
4911
4912 // Check whether the VD is move parameters.
4913 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4914 // The scope of parameter and move-parameter should be distinct
4915 // DISubprogram.
4916 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4917 return nullptr;
4918
4919 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4920 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4921 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4922 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4923 Decl *Decl = DeclGroup.getSingleDecl();
4924 if (VD == dyn_cast_or_null<VarDecl>(Decl))
4925 return true;
4926 }
4927 return false;
4928 });
4929
4930 if (Iter != CoroutineParameterMappings.end()) {
4931 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4932 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4933 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4934 });
4935 if (Iter2 != ParamDbgMappings.end())
4936 return const_cast<llvm::DILocalVariable *>(Iter2->second);
4937 }
4938 return nullptr;
4939 };
4940
4941 // If we couldn't find a move param DIVariable, create a new one.
4942 D = RemapCoroArgToLocalVar();
4943 // Or we will create a new DIVariable for this Decl if D dose not exists.
4944 if (!D)
4945 D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4946 CGM.getLangOpts().Optimize, Flags, Align);
4947 }
4948 // Insert an llvm.dbg.declare into the current block.
4949 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4950 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4951 Column, Scope, CurInlinedAt),
4952 Builder.GetInsertBlock());
4953
4954 return D;
4955}
4956
4957llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4958 llvm::Value *Storage,
4959 std::optional<unsigned> ArgNo,
4960 CGBuilderTy &Builder,
4961 const bool UsePointerValue) {
4962 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4963 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4964 if (BD->hasAttr<NoDebugAttr>())
4965 return nullptr;
4966
4967 // Skip the tuple like case, we don't handle that here
4968 if (isa<DeclRefExpr>(BD->getBinding()))
4969 return nullptr;
4970
4971 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4972 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
4973
4974 // If there is no debug info for this type then do not emit debug info
4975 // for this variable.
4976 if (!Ty)
4977 return nullptr;
4978
4979 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4980 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
4981
4983 AppendAddressSpaceXDeref(AddressSpace, Expr);
4984
4985 // Clang stores the sret pointer provided by the caller in a static alloca.
4986 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4987 // the address of the variable.
4988 if (UsePointerValue) {
4989 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4990 "Debug info already contains DW_OP_deref.");
4991 Expr.push_back(llvm::dwarf::DW_OP_deref);
4992 }
4993
4994 unsigned Line = getLineNumber(BD->getLocation());
4995 unsigned Column = getColumnNumber(BD->getLocation());
4996 StringRef Name = BD->getName();
4997 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4998 // Create the descriptor for the variable.
4999 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5000 Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
5001 llvm::DINode::FlagZero, Align);
5002
5003 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5004 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5005 const unsigned fieldIndex = FD->getFieldIndex();
5006 const clang::CXXRecordDecl *parent =
5007 (const CXXRecordDecl *)FD->getParent();
5008 const ASTRecordLayout &layout =
5009 CGM.getContext().getASTRecordLayout(parent);
5010 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5011 if (FD->isBitField()) {
5012 const CGRecordLayout &RL =
5013 CGM.getTypes().getCGRecordLayout(FD->getParent());
5014 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5015 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5016 // storage.
5017 if (!Info.StorageOffset.isZero()) {
5018 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5019 Expr.push_back(Info.StorageOffset.getQuantity());
5020 }
5021 // Use LLVM_extract_bits to extract the appropriate bits from this
5022 // bitfield.
5023 Expr.push_back(Info.IsSigned
5024 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5025 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5026 Expr.push_back(Info.Offset);
5027 // If we have an oversized bitfield then the value won't be more than
5028 // the size of the type.
5029 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5030 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5031 } else if (fieldOffset != 0) {
5032 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5033 "Unexpected non-bitfield with non-byte-aligned offset");
5034 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5035 Expr.push_back(
5036 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5037 }
5038 }
5039 } else if (const ArraySubscriptExpr *ASE =
5040 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5041 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5042 const uint64_t value = IL->getValue().getZExtValue();
5043 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5044
5045 if (value != 0) {
5046 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5047 Expr.push_back(CGM.getContext()
5048 .toCharUnitsFromBits(value * typeSize)
5049 .getQuantity());
5050 }
5051 }
5052 }
5053
5054 // Insert an llvm.dbg.declare into the current block.
5055 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5056 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5057 Column, Scope, CurInlinedAt),
5058 Builder.GetInsertBlock());
5059
5060 return D;
5061}
5062
5063llvm::DILocalVariable *
5064CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5065 CGBuilderTy &Builder,
5066 const bool UsePointerValue) {
5067 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5068
5069 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5070 for (auto *B : DD->bindings()) {
5071 EmitDeclare(B, Storage, std::nullopt, Builder,
5072 VD->getType()->isReferenceType());
5073 }
5074 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5075 // correspond to a user variable.
5076 return nullptr;
5077 }
5078
5079 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5080}
5081
5083 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5084 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5085
5086 if (D->hasAttr<NoDebugAttr>())
5087 return;
5088
5089 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5090 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5091
5092 // Get location information.
5093 unsigned Line = getLineNumber(D->getLocation());
5094 unsigned Column = getColumnNumber(D->getLocation());
5095
5096 StringRef Name = D->getName();
5097
5098 // Create the descriptor for the label.
5099 auto *L =
5100 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
5101
5102 // Insert an llvm.dbg.label into the current block.
5103 DBuilder.insertLabel(L,
5104 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5105 Scope, CurInlinedAt),
5106 Builder.GetInsertBlock());
5107}
5108
5109llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5110 llvm::DIType *Ty) {
5111 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5112 if (CachedTy)
5113 Ty = CachedTy;
5114 return DBuilder.createObjectPointerType(Ty);
5115}
5116
5118 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5119 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5120 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5121 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5122
5123 if (Builder.GetInsertBlock() == nullptr)
5124 return;
5125 if (VD->hasAttr<NoDebugAttr>())
5126 return;
5127
5128 bool isByRef = VD->hasAttr<BlocksAttr>();
5129
5130 uint64_t XOffset = 0;
5131 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5132 llvm::DIType *Ty;
5133 if (isByRef)
5134 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5135 else
5136 Ty = getOrCreateType(VD->getType(), Unit);
5137
5138 // Self is passed along as an implicit non-arg variable in a
5139 // block. Mark it as the object pointer.
5140 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5141 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5142 Ty = CreateSelfType(VD->getType(), Ty);
5143
5144 // Get location information.
5145 const unsigned Line =
5146 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5147 unsigned Column = getColumnNumber(VD->getLocation());
5148
5149 const llvm::DataLayout &target = CGM.getDataLayout();
5150
5152 target.getStructLayout(blockInfo.StructureType)
5153 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5154
5156 addr.push_back(llvm::dwarf::DW_OP_deref);
5157 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5158 addr.push_back(offset.getQuantity());
5159 if (isByRef) {
5160 addr.push_back(llvm::dwarf::DW_OP_deref);
5161 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5162 // offset of __forwarding field
5163 offset =
5164 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5165 addr.push_back(offset.getQuantity());
5166 addr.push_back(llvm::dwarf::DW_OP_deref);
5167 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5168 // offset of x field
5169 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5170 addr.push_back(offset.getQuantity());
5171 }
5172
5173 // Create the descriptor for the variable.
5174 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5175 auto *D = DBuilder.createAutoVariable(
5176 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5177 Line, Ty, false, llvm::DINode::FlagZero, Align);
5178
5179 // Insert an llvm.dbg.declare into the current block.
5180 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5181 LexicalBlockStack.back(), CurInlinedAt);
5182 auto *Expr = DBuilder.createExpression(addr);
5183 if (InsertPoint)
5184 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
5185 else
5186 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5187}
5188
5189llvm::DILocalVariable *
5191 unsigned ArgNo, CGBuilderTy &Builder,
5192 bool UsePointerValue) {
5193 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5194 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5195}
5196
5197namespace {
5198struct BlockLayoutChunk {
5199 uint64_t OffsetInBits;
5201};
5202bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5203 return l.OffsetInBits < r.OffsetInBits;
5204}
5205} // namespace
5206
5207void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5208 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5209 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5211 // Blocks in OpenCL have unique constraints which make the standard fields
5212 // redundant while requiring size and align fields for enqueue_kernel. See
5213 // initializeForBlockHeader in CGBlocks.cpp
5214 if (CGM.getLangOpts().OpenCL) {
5215 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5216 BlockLayout.getElementOffsetInBits(0),
5217 Unit, Unit));
5218 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5219 BlockLayout.getElementOffsetInBits(1),
5220 Unit, Unit));
5221 } else {
5222 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5223 BlockLayout.getElementOffsetInBits(0),
5224 Unit, Unit));
5225 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5226 BlockLayout.getElementOffsetInBits(1),
5227 Unit, Unit));
5228 Fields.push_back(
5229 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5230 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5231 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5232 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5233 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5234 BlockLayout.getElementOffsetInBits(3),
5235 Unit, Unit));
5236 Fields.push_back(createFieldType(
5237 "__descriptor",
5238 Context.getPointerType(Block.NeedsCopyDispose
5240 : Context.getBlockDescriptorType()),
5241 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5242 }
5243}
5244
5246 StringRef Name,
5247 unsigned ArgNo,
5248 llvm::AllocaInst *Alloca,
5249 CGBuilderTy &Builder) {
5250 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5251 ASTContext &C = CGM.getContext();
5252 const BlockDecl *blockDecl = block.getBlockDecl();
5253
5254 // Collect some general information about the block's location.
5255 SourceLocation loc = blockDecl->getCaretLocation();
5256 llvm::DIFile *tunit = getOrCreateFile(loc);
5257 unsigned line = getLineNumber(loc);
5258 unsigned column = getColumnNumber(loc);
5259
5260 // Build the debug-info type for the block literal.
5261 getDeclContextDescriptor(blockDecl);
5262
5263 const llvm::StructLayout *blockLayout =
5264 CGM.getDataLayout().getStructLayout(block.StructureType);
5265
5267 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5268 fields);
5269
5270 // We want to sort the captures by offset, not because DWARF
5271 // requires this, but because we're paranoid about debuggers.
5273
5274 // 'this' capture.
5275 if (blockDecl->capturesCXXThis()) {
5276 BlockLayoutChunk chunk;
5277 chunk.OffsetInBits =
5278 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5279 chunk.Capture = nullptr;
5280 chunks.push_back(chunk);
5281 }
5282
5283 // Variable captures.
5284 for (const auto &capture : blockDecl->captures()) {
5285 const VarDecl *variable = capture.getVariable();
5286 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5287
5288 // Ignore constant captures.
5289 if (captureInfo.isConstant())
5290 continue;
5291
5292 BlockLayoutChunk chunk;
5293 chunk.OffsetInBits =
5294 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5295 chunk.Capture = &capture;
5296 chunks.push_back(chunk);
5297 }
5298
5299 // Sort by offset.
5300 llvm::array_pod_sort(chunks.begin(), chunks.end());
5301
5302 for (const BlockLayoutChunk &Chunk : chunks) {
5303 uint64_t offsetInBits = Chunk.OffsetInBits;
5304 const BlockDecl::Capture *capture = Chunk.Capture;
5305
5306 // If we have a null capture, this must be the C++ 'this' capture.
5307 if (!capture) {
5308 QualType type;
5309 if (auto *Method =
5310 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5311 type = Method->getThisType();
5312 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5313 type = QualType(RDecl->getTypeForDecl(), 0);
5314 else
5315 llvm_unreachable("unexpected block declcontext");
5316
5317 fields.push_back(createFieldType("this", type, loc, AS_public,
5318 offsetInBits, tunit, tunit));
5319 continue;
5320 }
5321
5322 const VarDecl *variable = capture->getVariable();
5323 StringRef name = variable->getName();
5324
5325 llvm::DIType *fieldType;
5326 if (capture->isByRef()) {
5327 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5328 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5329 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5330 uint64_t xoffset;
5331 fieldType =
5332 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5333 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5334 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5335 PtrInfo.Width, Align, offsetInBits,
5336 llvm::DINode::FlagZero, fieldType);
5337 } else {
5338 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5339 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5340 offsetInBits, Align, tunit, tunit);
5341 }
5342 fields.push_back(fieldType);
5343 }
5344
5345 SmallString<36> typeName;
5346 llvm::raw_svector_ostream(typeName)
5347 << "__block_literal_" << CGM.getUniqueBlockCount();
5348
5349 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5350
5351 llvm::DIType *type =
5352 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5353 CGM.getContext().toBits(block.BlockSize), 0,
5354 llvm::DINode::FlagZero, nullptr, fieldsArray);
5355 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5356
5357 // Get overall information about the block.
5358 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5359 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5360
5361 // Create the descriptor for the parameter.
5362 auto *debugVar = DBuilder.createParameterVariable(
5363 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
5364
5365 // Insert an llvm.dbg.declare into the current block.
5366 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5367 llvm::DILocation::get(CGM.getLLVMContext(), line,
5368 column, scope, CurInlinedAt),
5369 Builder.GetInsertBlock());
5370}
5371
5372llvm::DIDerivedType *
5373CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5374 if (!D || !D->isStaticDataMember())
5375 return nullptr;
5376
5377 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5378 if (MI != StaticDataMemberCache.end()) {
5379 assert(MI->second && "Static data member declaration should still exist");
5380 return MI->second;
5381 }
5382
5383 // If the member wasn't found in the cache, lazily construct and add it to the
5384 // type (used when a limited form of the type is emitted).
5385 auto DC = D->getDeclContext();
5386 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5387 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5388}
5389
5390llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5391 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5392 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5393 llvm::DIGlobalVariableExpression *GVE = nullptr;
5394
5395 for (const auto *Field : RD->fields()) {
5396 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5397 StringRef FieldName = Field->getName();
5398
5399 // Ignore unnamed fields, but recurse into anonymous records.
5400 if (FieldName.empty()) {
5401 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5402 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
5403 Var, DContext);
5404 continue;
5405 }
5406 // Use VarDecl's Tag, Scope and Line number.
5407 GVE = DBuilder.createGlobalVariableExpression(
5408 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5409 Var->hasLocalLinkage());
5410 Var->addDebugInfo(GVE);
5411 }
5412 return GVE;
5413}
5414
5417 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5418 // info we produce in the DWARF, so we can't get Clang's full name back.
5419 // But so long as it's not one of those, it doesn't matter if some sub-type
5420 // of the record (a template parameter) can't be reconstituted - because the
5421 // un-reconstitutable type itself will carry its own name.
5422 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5423 if (!RD)
5424 return false;
5425 if (!RD->getIdentifier())
5426 return true;
5427 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5428 if (!TSpecial)
5429 return false;
5430 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5431}
5433 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5434 switch (TA.getKind()) {
5435 case TemplateArgument::Pack:
5436 return ReferencesAnonymousEntity(TA.getPackAsArray());
5437 case TemplateArgument::Type: {
5438 struct ReferencesAnonymous
5439 : public RecursiveASTVisitor<ReferencesAnonymous> {
5440 bool RefAnon = false;
5441 bool VisitRecordType(RecordType *RT) {
5442 if (ReferencesAnonymousEntity(RT)) {
5443 RefAnon = true;
5444 return false;
5445 }
5446 return true;
5447 }
5448 };
5449 ReferencesAnonymous RT;
5450 RT.TraverseType(TA.getAsType());
5451 if (RT.RefAnon)
5452 return true;
5453 break;
5454 }
5455 default:
5456 break;
5457 }
5458 return false;
5459 });
5460}
5461namespace {
5462struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5463 bool Reconstitutable = true;
5464 bool VisitVectorType(VectorType *FT) {
5465 Reconstitutable = false;
5466 return false;
5467 }
5468 bool VisitAtomicType(AtomicType *FT) {
5469 Reconstitutable = false;
5470 return false;
5471 }
5472 bool VisitType(Type *T) {
5473 // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5474 // the DWARF, only the byte width.
5475 if (T->isBitIntType()) {
5476 Reconstitutable = false;
5477 return false;
5478 }
5479 return true;
5480 }
5481 bool TraverseEnumType(EnumType *ET) {
5482 // Unnamed enums can't be reconstituted due to a lack of column info we
5483 // produce in the DWARF, so we can't get Clang's full name back.
5484 if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5485 if (!ED->getIdentifier()) {
5486 Reconstitutable = false;
5487 return false;
5488 }
5489 if (!ED->isExternallyVisible()) {
5490 Reconstitutable = false;
5491 return false;
5492 }
5493 }
5494 return true;
5495 }
5496 bool VisitFunctionProtoType(FunctionProtoType *FT) {
5497 // noexcept is not encoded in DWARF, so the reversi
5498 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5499 Reconstitutable &= !FT->getNoReturnAttr();
5500 return Reconstitutable;
5501 }
5502 bool VisitRecordType(RecordType *RT) {
5503 if (ReferencesAnonymousEntity(RT)) {
5504 Reconstitutable = false;
5505 return false;
5506 }
5507 return true;
5508 }
5509};
5510} // anonymous namespace
5511
5512// Test whether a type name could be rebuilt from emitted debug info.
5514 ReconstitutableType T;
5515 T.TraverseType(QT);
5516 return T.Reconstitutable;
5517}
5518
5519bool CGDebugInfo::HasReconstitutableArgs(
5520 ArrayRef<TemplateArgument> Args) const {
5521 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5522 switch (TA.getKind()) {
5523 case TemplateArgument::Template:
5524 // Easy to reconstitute - the value of the parameter in the debug
5525 // info is the string name of the template. The template name
5526 // itself won't benefit from any name rebuilding, but that's a
5527 // representational limitation - maybe DWARF could be
5528 // changed/improved to use some more structural representation.
5529 return true;
5530 case TemplateArgument::Declaration:
5531 // Reference and pointer non-type template parameters point to
5532 // variables, functions, etc and their value is, at best (for
5533 // variables) represented as an address - not a reference to the
5534 // DWARF describing the variable/function/etc. This makes it hard,
5535 // possibly impossible to rebuild the original name - looking up
5536 // the address in the executable file's symbol table would be
5537 // needed.
5538 return false;
5539 case TemplateArgument::NullPtr:
5540 // These could be rebuilt, but figured they're close enough to the
5541 // declaration case, and not worth rebuilding.
5542 return false;
5543 case TemplateArgument::Pack:
5544 // A pack is invalid if any of the elements of the pack are
5545 // invalid.
5546 return HasReconstitutableArgs(TA.getPackAsArray());
5547 case TemplateArgument::Integral:
5548 // Larger integers get encoded as DWARF blocks which are a bit
5549 // harder to parse back into a large integer, etc - so punting on
5550 // this for now. Re-parsing the integers back into APInt is
5551 // probably feasible some day.
5552 return TA.getAsIntegral().getBitWidth() <= 64 &&
5553 IsReconstitutableType(TA.getIntegralType());
5554 case TemplateArgument::StructuralValue:
5555 return false;
5556 case TemplateArgument::Type:
5557 return IsReconstitutableType(TA.getAsType());
5558 case TemplateArgument::Expression:
5559 return IsReconstitutableType(TA.getAsExpr()->getType());
5560 default:
5561 llvm_unreachable("Other, unresolved, template arguments should "
5562 "not be seen here");
5563 }
5564 });
5565}
5566
5567std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5568 std::string Name;
5569 llvm::raw_string_ostream OS(Name);
5570 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5571 if (!ND)
5572 return Name;
5573 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5574 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5575
5577 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
5578
5579 std::optional<TemplateArgs> Args;
5580
5581 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5582 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5583 Args = GetTemplateArgs(RD);
5584 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5585 Args = GetTemplateArgs(FD);
5586 auto NameKind = ND->getDeclName().getNameKind();
5587 IsOperatorOverload |=
5590 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5591 Args = GetTemplateArgs(VD);
5592 }
5593
5594 // A conversion operator presents complications/ambiguity if there's a
5595 // conversion to class template that is itself a template, eg:
5596 // template<typename T>
5597 // operator ns::t1<T, int>();
5598 // This should be named, eg: "operator ns::t1<float, int><float>"
5599 // (ignoring clang bug that means this is currently "operator t1<float>")
5600 // but if the arguments were stripped, the consumer couldn't differentiate
5601 // whether the template argument list for the conversion type was the
5602 // function's argument list (& no reconstitution was needed) or not.
5603 // This could be handled if reconstitutable names had a separate attribute
5604 // annotating them as such - this would remove the ambiguity.
5605 //
5606 // Alternatively the template argument list could be parsed enough to check
5607 // whether there's one list or two, then compare that with the DWARF
5608 // description of the return type and the template argument lists to determine
5609 // how many lists there should be and if one is missing it could be assumed(?)
5610 // to be the function's template argument list & then be rebuilt.
5611 //
5612 // Other operator overloads that aren't conversion operators could be
5613 // reconstituted but would require a bit more nuance about detecting the
5614 // difference between these different operators during that rebuilding.
5615 bool Reconstitutable =
5616 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5617
5618 PrintingPolicy PP = getPrintingPolicy();
5619
5620 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
5621 !Reconstitutable) {
5622 ND->getNameForDiagnostic(OS, PP, Qualified);
5623 } else {
5624 bool Mangled = TemplateNamesKind ==
5625 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
5626 // check if it's a template
5627 if (Mangled)
5628 OS << "_STN|";
5629
5630 OS << ND->getDeclName();
5631 std::string EncodedOriginalName;
5632 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5633 EncodedOriginalNameOS << ND->getDeclName();
5634
5635 if (Mangled) {
5636 OS << "|";
5637 printTemplateArgumentList(OS, Args->Args, PP);
5638 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5639#ifndef NDEBUG
5640 std::string CanonicalOriginalName;
5641 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5642 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5643 assert(EncodedOriginalName == CanonicalOriginalName);
5644#endif
5645 }
5646 }
5647 return Name;
5648}
5649
5650void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5651 const VarDecl *D) {
5652 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5653 if (D->hasAttr<NoDebugAttr>())
5654 return;
5655
5656 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5657 return GetName(D, true);
5658 });
5659
5660 // If we already created a DIGlobalVariable for this declaration, just attach
5661 // it to the llvm::GlobalVariable.
5662 auto Cached = DeclCache.find(D->getCanonicalDecl());
5663 if (Cached != DeclCache.end())
5664 return Var->addDebugInfo(
5665 cast<llvm::DIGlobalVariableExpression>(Cached->second));
5666
5667 // Create global variable debug descriptor.
5668 llvm::DIFile *Unit = nullptr;
5669 llvm::DIScope *DContext = nullptr;
5670 unsigned LineNo;
5671 StringRef DeclName, LinkageName;
5672 QualType T;
5673 llvm::MDTuple *TemplateParameters = nullptr;
5674 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5675 TemplateParameters, DContext);
5676
5677 // Attempt to store one global variable for the declaration - even if we
5678 // emit a lot of fields.
5679 llvm::DIGlobalVariableExpression *GVE = nullptr;
5680
5681 // If this is an anonymous union then we'll want to emit a global
5682 // variable for each member of the anonymous union so that it's possible
5683 // to find the name of any field in the union.
5684 if (T->isUnionType() && DeclName.empty()) {
5685 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5686 assert(RD->isAnonymousStructOrUnion() &&
5687 "unnamed non-anonymous struct or union?");
5688 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5689 } else {
5690 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5691
5693 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
5694 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5695 if (D->hasAttr<CUDASharedAttr>())
5696 AddressSpace =
5698 else if (D->hasAttr<CUDAConstantAttr>())
5699 AddressSpace =
5701 }
5702 AppendAddressSpaceXDeref(AddressSpace, Expr);
5703
5704 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5705 GVE = DBuilder.createGlobalVariableExpression(
5706 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5707 Var->hasLocalLinkage(), true,
5708 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5709 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5710 Align, Annotations);
5711 Var->addDebugInfo(GVE);
5712 }
5713 DeclCache[D->getCanonicalDecl()].reset(GVE);
5714}
5715
5717 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5718 if (VD->hasAttr<NoDebugAttr>())
5719 return;
5720 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5721 return GetName(VD, true);
5722 });
5723
5724 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5725 // Create the descriptor for the variable.
5726 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5727 StringRef Name = VD->getName();
5728 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5729
5730 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5731 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5732 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5733
5734 if (CGM.getCodeGenOpts().EmitCodeView) {
5735 // If CodeView, emit enums as global variables, unless they are defined
5736 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5737 // enums in classes, and because it is difficult to attach this scope
5738 // information to the global variable.
5739 if (isa<RecordDecl>(ED->getDeclContext()))
5740 return;
5741 } else {
5742 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5743 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5744 // first time `ZERO` is referenced in a function.
5745 llvm::DIType *EDTy =
5746 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5747 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5748 (void)EDTy;
5749 return;
5750 }
5751 }
5752
5753 // Do not emit separate definitions for function local consts.
5754 if (isa<FunctionDecl>(VD->getDeclContext()))
5755 return;
5756
5757 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5758 auto *VarD = dyn_cast<VarDecl>(VD);
5759 if (VarD && VarD->isStaticDataMember()) {
5760 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5761 getDeclContextDescriptor(VarD);
5762 // Ensure that the type is retained even though it's otherwise unreferenced.
5763 //
5764 // FIXME: This is probably unnecessary, since Ty should reference RD
5765 // through its scope.
5766 RetainedTypes.push_back(
5768
5769 return;
5770 }
5771 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5772
5773 auto &GV = DeclCache[VD];
5774 if (GV)
5775 return;
5776
5777 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
5778 llvm::MDTuple *TemplateParameters = nullptr;
5779
5780 if (isa<VarTemplateSpecializationDecl>(VD))
5781 if (VarD) {
5782 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5783 TemplateParameters = parameterNodes.get();
5784 }
5785
5786 GV.reset(DBuilder.createGlobalVariableExpression(
5787 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5788 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5789 TemplateParameters, Align));
5790}
5791
5792void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5793 const VarDecl *D) {
5794 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5795 if (D->hasAttr<NoDebugAttr>())
5796 return;
5797
5798 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5799 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5800 StringRef Name = D->getName();
5801 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5802
5803 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5804 llvm::DIGlobalVariableExpression *GVE =
5805 DBuilder.createGlobalVariableExpression(
5806 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5807 Ty, false, false, nullptr, nullptr, nullptr, Align);
5808 Var->addDebugInfo(GVE);
5809}
5810
5812 llvm::Instruction *Value, QualType Ty) {
5813 // Only when -g2 or above is specified, debug info for variables will be
5814 // generated.
5815 if (CGM.getCodeGenOpts().getDebugInfo() <=
5816 llvm::codegenoptions::DebugLineTablesOnly)
5817 return;
5818
5819 llvm::DILocation *DIL = Value->getDebugLoc().get();
5820 if (!DIL)
5821 return;
5822
5823 llvm::DIFile *Unit = DIL->getFile();
5824 llvm::DIType *Type = getOrCreateType(Ty, Unit);
5825
5826 // Check if Value is already a declared variable and has debug info, in this
5827 // case we have nothing to do. Clang emits a declared variable as alloca, and
5828 // it is loaded upon use, so we identify such pattern here.
5829 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
5830 llvm::Value *Var = Load->getPointerOperand();
5831 // There can be implicit type cast applied on a variable if it is an opaque
5832 // ptr, in this case its debug info may not match the actual type of object
5833 // being used as in the next instruction, so we will need to emit a pseudo
5834 // variable for type-casted value.
5835 auto DeclareTypeMatches = [&](auto *DbgDeclare) {
5836 return DbgDeclare->getVariable()->getType() == Type;
5837 };
5838 if (any_of(llvm::findDbgDeclares(Var), DeclareTypeMatches) ||
5839 any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
5840 return;
5841 }
5842
5843 llvm::DILocalVariable *D =
5844 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
5845 Type, false, llvm::DINode::FlagArtificial);
5846
5847 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
5848 DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,
5849 &**InsertPoint);
5850 }
5851}
5852
5853void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5854 const GlobalDecl GD) {
5855
5856 assert(GV);
5857
5859 return;
5860
5861 const auto *D = cast<ValueDecl>(GD.getDecl());
5862 if (D->hasAttr<NoDebugAttr>())
5863 return;
5864
5865 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5866 llvm::DINode *DI;
5867
5868 if (!AliaseeDecl)
5869 // FIXME: Aliasee not declared yet - possibly declared later
5870 // For example,
5871 //
5872 // 1 extern int newname __attribute__((alias("oldname")));
5873 // 2 int oldname = 1;
5874 //
5875 // No debug info would be generated for 'newname' in this case.
5876 //
5877 // Fix compiler to generate "newname" as imported_declaration
5878 // pointing to the DIE of "oldname".
5879 return;
5880 if (!(DI = getDeclarationOrDefinition(
5881 AliaseeDecl.getCanonicalDecl().getDecl())))
5882 return;
5883
5884 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5885 auto Loc = D->getLocation();
5886
5887 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5888 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5889
5890 // Record this DIE in the cache for nested declaration reference.
5891 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5892}
5893
5894void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
5895 const StringLiteral *S) {
5896 SourceLocation Loc = S->getStrTokenLoc(0);
5898 if (!PLoc.isValid())
5899 return;
5900
5901 llvm::DIFile *File = getOrCreateFile(Loc);
5902 llvm::DIGlobalVariableExpression *Debug =
5903 DBuilder.createGlobalVariableExpression(
5904 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
5905 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
5906 GV->addDebugInfo(Debug);
5907}
5908
5909llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5910 if (!LexicalBlockStack.empty())
5911 return LexicalBlockStack.back();
5912 llvm::DIScope *Mod = getParentModuleOrNull(D);
5913 return getContextDescriptor(D, Mod ? Mod : TheCU);
5914}
5915
5918 return;
5919 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5920 if (!NSDecl->isAnonymousNamespace() ||
5921 CGM.getCodeGenOpts().DebugExplicitImport) {
5922 auto Loc = UD.getLocation();
5923 if (!Loc.isValid())
5924 Loc = CurLoc;
5925 DBuilder.createImportedModule(
5926 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5927 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5928 }
5929}
5930
5932 if (llvm::DINode *Target =
5933 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5934 auto Loc = USD.getLocation();
5935 DBuilder.createImportedDeclaration(
5936 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5937 getOrCreateFile(Loc), getLineNumber(Loc));
5938 }
5939}
5940
5943 return;
5944 assert(UD.shadow_size() &&
5945 "We shouldn't be codegening an invalid UsingDecl containing no decls");
5946
5947 for (const auto *USD : UD.shadows()) {
5948 // FIXME: Skip functions with undeduced auto return type for now since we
5949 // don't currently have the plumbing for separate declarations & definitions
5950 // of free functions and mismatched types (auto in the declaration, concrete
5951 // return type in the definition)
5952 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5953 if (const auto *AT = FD->getType()
5954 ->castAs<FunctionProtoType>()
5956 if (AT->getDeducedType().isNull())
5957 continue;
5958
5959 EmitUsingShadowDecl(*USD);
5960 // Emitting one decl is sufficient - debuggers can detect that this is an
5961 // overloaded name & provide lookup for all the overloads.
5962 break;
5963 }
5964}
5965
5968 return;
5969 assert(UD.shadow_size() &&
5970 "We shouldn't be codegening an invalid UsingEnumDecl"
5971 " containing no decls");
5972
5973 for (const auto *USD : UD.shadows())
5974 EmitUsingShadowDecl(*USD);
5975}
5976
5978 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5979 return;
5980 if (Module *M = ID.getImportedModule()) {
5981 auto Info = ASTSourceDescriptor(*M);
5982 auto Loc = ID.getLocation();
5983 DBuilder.createImportedDeclaration(
5984 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5985 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5986 getLineNumber(Loc));
5987 }
5988}
5989
5990llvm::DIImportedEntity *
5993 return nullptr;
5994 auto &VH = NamespaceAliasCache[&NA];
5995 if (VH)
5996 return cast<llvm::DIImportedEntity>(VH);
5997 llvm::DIImportedEntity *R;
5998 auto Loc = NA.getLocation();
5999 if (const auto *Underlying =
6000 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6001 // This could cache & dedup here rather than relying on metadata deduping.
6002 R = DBuilder.createImportedDeclaration(
6003 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6004 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6005 getLineNumber(Loc), NA.getName());
6006 else
6007 R = DBuilder.createImportedDeclaration(
6008 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6009 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6010 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6011 VH.reset(R);
6012 return R;
6013}
6014
6015llvm::DINamespace *
6016CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6017 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6018 // if necessary, and this way multiple declarations of the same namespace in
6019 // different parent modules stay distinct.
6020 auto I = NamespaceCache.find(NSDecl);
6021 if (I != NamespaceCache.end())
6022 return cast<llvm::DINamespace>(I->second);
6023
6024 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6025 // Don't trust the context if it is a DIModule (see comment above).
6026 llvm::DINamespace *NS =
6027 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6028 NamespaceCache[NSDecl].reset(NS);
6029 return NS;
6030}
6031
6032void CGDebugInfo::setDwoId(uint64_t Signature) {
6033 assert(TheCU && "no main compile unit");
6034 TheCU->setDWOId(Signature);
6035}
6036
6038 // Creating types might create further types - invalidating the current
6039 // element and the size(), so don't cache/reference them.
6040 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6041 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6042 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6043 ? CreateTypeDefinition(E.Type, E.Unit)
6044 : E.Decl;
6045 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6046 }
6047
6048 // Add methods to interface.
6049 for (const auto &P : ObjCMethodCache) {
6050 if (P.second.empty())
6051 continue;
6052
6053 QualType QTy(P.first->getTypeForDecl(), 0);
6054 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6055 assert(It != TypeCache.end());
6056
6057 llvm::DICompositeType *InterfaceDecl =
6058 cast<llvm::DICompositeType>(It->second);
6059
6060 auto CurElts = InterfaceDecl->getElements();
6061 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6062
6063 // For DWARF v4 or earlier, only add objc_direct methods.
6064 for (auto &SubprogramDirect : P.second)
6065 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6066 EltTys.push_back(SubprogramDirect.getPointer());
6067
6068 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6069 DBuilder.replaceArrays(InterfaceDecl, Elements);
6070 }
6071
6072 for (const auto &P : ReplaceMap) {
6073 assert(P.second);
6074 auto *Ty = cast<llvm::DIType>(P.second);
6075 assert(Ty->isForwardDecl());
6076
6077 auto It = TypeCache.find(P.first);
6078 assert(It != TypeCache.end());
6079 assert(It->second);
6080
6081 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6082 cast<llvm::DIType>(It->second));
6083 }
6084
6085 for (const auto &P : FwdDeclReplaceMap) {
6086 assert(P.second);
6087 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6088 llvm::Metadata *Repl;
6089
6090 auto It = DeclCache.find(P.first);
6091 // If there has been no definition for the declaration, call RAUW
6092 // with ourselves, that will destroy the temporary MDNode and
6093 // replace it with a standard one, avoiding leaking memory.
6094 if (It == DeclCache.end())
6095 Repl = P.second;
6096 else
6097 Repl = It->second;
6098
6099 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6100 Repl = GVE->getVariable();
6101 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6102 }
6103
6104 // We keep our own list of retained types, because we need to look
6105 // up the final type in the type cache.
6106 for (auto &RT : RetainedTypes)
6107 if (auto MD = TypeCache[RT])
6108 DBuilder.retainType(cast<llvm::DIType>(MD));
6109
6110 DBuilder.finalize();
6111}
6112
6113// Don't ignore in case of explicit cast where it is referenced indirectly.
6116 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6117 DBuilder.retainType(DieTy);
6118}
6119
6122 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6123 DBuilder.retainType(DieTy);
6124}
6125
6127 if (LexicalBlockStack.empty())
6128 return llvm::DebugLoc();
6129
6130 llvm::MDNode *Scope = LexicalBlockStack.back();
6131 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6132 getColumnNumber(Loc), Scope);
6133}
6134
6135llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6136 // Call site-related attributes are only useful in optimized programs, and
6137 // when there's a possibility of debugging backtraces.
6138 if (!CGM.getLangOpts().Optimize ||
6139 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6140 DebugKind == llvm::codegenoptions::LocTrackingOnly)
6141 return llvm::DINode::FlagZero;
6142
6143 // Call site-related attributes are available in DWARF v5. Some debuggers,
6144 // while not fully DWARF v5-compliant, may accept these attributes as if they
6145 // were part of DWARF v4.
6146 bool SupportsDWARFv4Ext =
6147 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6148 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6149 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6150
6151 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6152 return llvm::DINode::FlagZero;
6153
6154 return llvm::DINode::FlagAllCallsDescribed;
6155}
6156
6157llvm::DIExpression *
6158CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6159 const APValue &Val) {
6160 // FIXME: Add a representation for integer constants wider than 64 bits.
6161 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6162 return nullptr;
6163
6164 if (Val.isFloat())
6165 return DBuilder.createConstantValueExpression(
6166 Val.getFloat().bitcastToAPInt().getZExtValue());
6167
6168 if (!Val.isInt())
6169 return nullptr;
6170
6171 llvm::APSInt const &ValInt = Val.getInt();
6172 std::optional<uint64_t> ValIntOpt;
6173 if (ValInt.isUnsigned())
6174 ValIntOpt = ValInt.tryZExtValue();
6175 else if (auto tmp = ValInt.trySExtValue())
6176 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6177 // use std::optional::transform
6178 ValIntOpt = static_cast<uint64_t>(*tmp);
6179
6180 if (ValIntOpt)
6181 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6182
6183 return nullptr;
6184}
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:3035
StringRef Identifier
Definition: Format.cpp:3040
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:458
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:455
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
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