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