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
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
1318 assert(Ty->isTypeAlias());
1319 // TemplateSpecializationType doesn't know if its template args are
1320 // being substituted into a parameter pack. We can find out if that's
1321 // the case now by inspecting the TypeAliasTemplateDecl template
1322 // parameters. Insert Ty's template args into SpecArgs, bundling args
1323 // passed to a parameter pack into a TemplateArgument::Pack. It also
1324 // doesn't know the value of any defaulted args, so collect those now
1325 // too.
1327 ArrayRef SubstArgs = Ty->template_arguments();
1328 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1329 // If Param is a parameter pack, pack the remaining arguments.
1330 if (Param->isParameterPack()) {
1331 SpecArgs.push_back(TemplateArgument(SubstArgs));
1332 break;
1333 }
1334
1335 // Skip defaulted args.
1336 // FIXME: Ideally, we wouldn't do this. We can read the default values
1337 // for each parameter. However, defaulted arguments which are dependent
1338 // values or dependent types can't (easily?) be resolved here.
1339 if (SubstArgs.empty()) {
1340 // If SubstArgs is now empty (we're taking from it each iteration) and
1341 // this template parameter isn't a pack, then that should mean we're
1342 // using default values for the remaining template parameters (after
1343 // which there may be an empty pack too which we will ignore).
1344 break;
1345 }
1346
1347 // Take the next argument.
1348 SpecArgs.push_back(SubstArgs.front());
1349 SubstArgs = SubstArgs.drop_front();
1350 }
1351 return SpecArgs;
1352}
1353
1354llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1355 llvm::DIFile *Unit) {
1356 assert(Ty->isTypeAlias());
1357 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1358
1360 if (isa<BuiltinTemplateDecl>(TD))
1361 return Src;
1362
1363 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1364 if (AliasDecl->hasAttr<NoDebugAttr>())
1365 return Src;
1366
1368 llvm::raw_svector_ostream OS(NS);
1369
1370 auto PP = getPrintingPolicy();
1372
1373 SourceLocation Loc = AliasDecl->getLocation();
1374
1375 if (CGM.getCodeGenOpts().DebugTemplateAlias &&
1376 // FIXME: This is a workaround for the issue
1377 // https://github.com/llvm/llvm-project/issues/89774
1378 // The TemplateSpecializationType doesn't contain any instantiation
1379 // information; dependent template arguments can't be resolved. For now,
1380 // fall back to DW_TAG_typedefs for template aliases that are
1381 // instantiation dependent, e.g.:
1382 // ```
1383 // template <int>
1384 // using A = int;
1385 //
1386 // template<int I>
1387 // struct S {
1388 // using AA = A<I>; // Instantiation dependent.
1389 // AA aa;
1390 // };
1391 //
1392 // S<0> s;
1393 // ```
1394 // S::AA's underlying type A<I> is dependent on I so will be emitted as a
1395 // DW_TAG_typedef.
1397 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1398 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1399
1400 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1401 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1402 // doesn't have instantiation information, so
1403 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1404 // template args.
1405 std::string Name;
1406 llvm::raw_string_ostream OS(Name);
1407 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1408 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1409 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1410 !HasReconstitutableArgs(Args.Args))
1411 printTemplateArgumentList(OS, Args.Args, PP);
1412
1413 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1414 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1415 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1416 return AliasTy;
1417 }
1418
1419 // Disable PrintCanonicalTypes here because we want
1420 // the DW_AT_name to benefit from the TypePrinter's ability
1421 // to skip defaulted template arguments.
1422 //
1423 // FIXME: Once -gsimple-template-names is enabled by default
1424 // and we attach template parameters to alias template DIEs
1425 // we don't need to worry about customizing the PrintingPolicy
1426 // here anymore.
1427 PP.PrintCanonicalTypes = false;
1429 TD->getTemplateParameters());
1430 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1431 getLineNumber(Loc),
1432 getDeclContextDescriptor(AliasDecl));
1433}
1434
1435/// Convert an AccessSpecifier into the corresponding DINode flag.
1436/// As an optimization, return 0 if the access specifier equals the
1437/// default for the containing type.
1438static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1439 const RecordDecl *RD) {
1441 if (RD && RD->isClass())
1443 else if (RD && (RD->isStruct() || RD->isUnion()))
1445
1446 if (Access == Default)
1447 return llvm::DINode::FlagZero;
1448
1449 switch (Access) {
1450 case clang::AS_private:
1451 return llvm::DINode::FlagPrivate;
1453 return llvm::DINode::FlagProtected;
1454 case clang::AS_public:
1455 return llvm::DINode::FlagPublic;
1456 case clang::AS_none:
1457 return llvm::DINode::FlagZero;
1458 }
1459 llvm_unreachable("unexpected access enumerator");
1460}
1461
1462llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1463 llvm::DIFile *Unit) {
1464 llvm::DIType *Underlying =
1465 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1466
1467 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1468 return Underlying;
1469
1470 // We don't set size information, but do specify where the typedef was
1471 // declared.
1473
1474 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1475 // Typedefs are derived from some other type.
1476 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1477
1478 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1479 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1480 if (isa<RecordDecl>(DC))
1481 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1482
1483 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1484 getOrCreateFile(Loc), getLineNumber(Loc),
1485 getDeclContextDescriptor(Ty->getDecl()), Align,
1486 Flags, Annotations);
1487}
1488
1489static unsigned getDwarfCC(CallingConv CC) {
1490 switch (CC) {
1491 case CC_C:
1492 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1493 return 0;
1494
1495 case CC_X86StdCall:
1496 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1497 case CC_X86FastCall:
1498 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1499 case CC_X86ThisCall:
1500 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1501 case CC_X86VectorCall:
1502 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1503 case CC_X86Pascal:
1504 return llvm::dwarf::DW_CC_BORLAND_pascal;
1505 case CC_Win64:
1506 return llvm::dwarf::DW_CC_LLVM_Win64;
1507 case CC_X86_64SysV:
1508 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1509 case CC_AAPCS:
1511 case CC_AArch64SVEPCS:
1512 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1513 case CC_AAPCS_VFP:
1514 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1515 case CC_IntelOclBicc:
1516 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1517 case CC_SpirFunction:
1518 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1519 case CC_OpenCLKernel:
1521 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1522 case CC_Swift:
1523 return llvm::dwarf::DW_CC_LLVM_Swift;
1524 case CC_SwiftAsync:
1525 return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1526 case CC_PreserveMost:
1527 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1528 case CC_PreserveAll:
1529 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1530 case CC_X86RegCall:
1531 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1532 case CC_M68kRTD:
1533 return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1534 case CC_PreserveNone:
1535 return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1536 case CC_RISCVVectorCall:
1537 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1538 }
1539 return 0;
1540}
1541
1542static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1543 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1544 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1545 Flags |= llvm::DINode::FlagLValueReference;
1546 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1547 Flags |= llvm::DINode::FlagRValueReference;
1548 return Flags;
1549}
1550
1551llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1552 llvm::DIFile *Unit) {
1553 const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1554 if (FPT) {
1555 if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1556 return QTy;
1557 }
1558
1559 // Create the type without any qualifiers
1560
1562
1563 // Add the result type at least.
1564 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1565
1566 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1567 // Set up remainder of arguments if there is a prototype.
1568 // otherwise emit it as a variadic function.
1569 if (!FPT) {
1570 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1571 } else {
1572 Flags = getRefFlags(FPT);
1573 for (const QualType &ParamType : FPT->param_types())
1574 EltTys.push_back(getOrCreateType(ParamType, Unit));
1575 if (FPT->isVariadic())
1576 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1577 }
1578
1579 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1580 llvm::DIType *F = DBuilder.createSubroutineType(
1581 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1582 return F;
1583}
1584
1585llvm::DIDerivedType *
1586CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1587 llvm::DIScope *RecordTy, const RecordDecl *RD) {
1588 StringRef Name = BitFieldDecl->getName();
1589 QualType Ty = BitFieldDecl->getType();
1590 if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1591 Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1592 SourceLocation Loc = BitFieldDecl->getLocation();
1593 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1594 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1595
1596 // Get the location for the field.
1597 llvm::DIFile *File = getOrCreateFile(Loc);
1598 unsigned Line = getLineNumber(Loc);
1599
1600 const CGBitFieldInfo &BitFieldInfo =
1601 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1602 uint64_t SizeInBits = BitFieldInfo.Size;
1603 assert(SizeInBits > 0 && "found named 0-width bitfield");
1604 uint64_t StorageOffsetInBits =
1605 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1606 uint64_t Offset = BitFieldInfo.Offset;
1607 // The bit offsets for big endian machines are reversed for big
1608 // endian target, compensate for that as the DIDerivedType requires
1609 // un-reversed offsets.
1610 if (CGM.getDataLayout().isBigEndian())
1611 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1612 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1613 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1614 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1615 return DBuilder.createBitFieldMemberType(
1616 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1617 Flags, DebugType, Annotations);
1618}
1619
1620llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1621 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1622 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1623
1625 return nullptr;
1626
1627 /*
1628 Add a *single* zero-bitfield separator between two non-zero bitfields
1629 separated by one or more zero-bitfields. This is used to distinguish between
1630 structures such the ones below, where the memory layout is the same, but how
1631 the ABI assigns fields to registers differs.
1632
1633 struct foo {
1634 int space[4];
1635 char a : 8; // on amdgpu, passed on v4
1636 char b : 8;
1637 char x : 8;
1638 char y : 8;
1639 };
1640 struct bar {
1641 int space[4];
1642 char a : 8; // on amdgpu, passed on v4
1643 char b : 8;
1644 char : 0;
1645 char x : 8; // passed on v5
1646 char y : 8;
1647 };
1648 */
1649 if (PreviousFieldsDI.empty())
1650 return nullptr;
1651
1652 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1653 auto *PreviousMDEntry =
1654 PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1655 auto *PreviousMDField =
1656 dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1657 if (!PreviousMDField || !PreviousMDField->isBitField() ||
1658 PreviousMDField->getSizeInBits() == 0)
1659 return nullptr;
1660
1661 auto PreviousBitfield = RD->field_begin();
1662 std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1663
1664 assert(PreviousBitfield->isBitField());
1665
1666 ASTContext &Context = CGM.getContext();
1667 if (!PreviousBitfield->isZeroLengthBitField(Context))
1668 return nullptr;
1669
1670 QualType Ty = PreviousBitfield->getType();
1671 SourceLocation Loc = PreviousBitfield->getLocation();
1672 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1673 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1674 llvm::DIScope *RecordTy = BitFieldDI->getScope();
1675
1676 llvm::DIFile *File = getOrCreateFile(Loc);
1677 unsigned Line = getLineNumber(Loc);
1678
1679 uint64_t StorageOffsetInBits =
1680 cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1681 ->getZExtValue();
1682
1683 llvm::DINode::DIFlags Flags =
1684 getAccessFlag(PreviousBitfield->getAccess(), RD);
1685 llvm::DINodeArray Annotations =
1686 CollectBTFDeclTagAnnotations(*PreviousBitfield);
1687 return DBuilder.createBitFieldMemberType(
1688 RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
1689 Flags, DebugType, Annotations);
1690}
1691
1692llvm::DIType *CGDebugInfo::createFieldType(
1693 StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1694 uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1695 llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1696 llvm::DIType *debugType = getOrCreateType(type, tunit);
1697
1698 // Get the location for the field.
1699 llvm::DIFile *file = getOrCreateFile(loc);
1700 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1701
1702 uint64_t SizeInBits = 0;
1703 auto Align = AlignInBits;
1704 if (!type->isIncompleteArrayType()) {
1705 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1706 SizeInBits = TI.Width;
1707 if (!Align)
1708 Align = getTypeAlignIfRequired(type, CGM.getContext());
1709 }
1710
1711 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1712 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1713 offsetInBits, flags, debugType, Annotations);
1714}
1715
1716void CGDebugInfo::CollectRecordLambdaFields(
1717 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1718 llvm::DIType *RecordTy) {
1719 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1720 // has the name and the location of the variable so we should iterate over
1721 // both concurrently.
1722 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1724 unsigned fieldno = 0;
1726 E = CXXDecl->captures_end();
1727 I != E; ++I, ++Field, ++fieldno) {
1728 const LambdaCapture &C = *I;
1729 if (C.capturesVariable()) {
1730 SourceLocation Loc = C.getLocation();
1731 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1732 ValueDecl *V = C.getCapturedVar();
1733 StringRef VName = V->getName();
1734 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1735 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1736 llvm::DIType *FieldType = createFieldType(
1737 VName, Field->getType(), Loc, Field->getAccess(),
1738 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1739 elements.push_back(FieldType);
1740 } else if (C.capturesThis()) {
1741 // TODO: Need to handle 'this' in some way by probably renaming the
1742 // this of the lambda class and having a field member of 'this' or
1743 // by using AT_object_pointer for the function and having that be
1744 // used as 'this' for semantic references.
1745 FieldDecl *f = *Field;
1746 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1747 QualType type = f->getType();
1748 StringRef ThisName =
1749 CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
1750 llvm::DIType *fieldType = createFieldType(
1751 ThisName, type, f->getLocation(), f->getAccess(),
1752 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1753
1754 elements.push_back(fieldType);
1755 }
1756 }
1757}
1758
1759llvm::DIDerivedType *
1760CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1761 const RecordDecl *RD) {
1762 // Create the descriptor for the static variable, with or without
1763 // constant initializers.
1764 Var = Var->getCanonicalDecl();
1765 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1766 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1767
1768 unsigned LineNumber = getLineNumber(Var->getLocation());
1769 StringRef VName = Var->getName();
1770
1771 // FIXME: to avoid complications with type merging we should
1772 // emit the constant on the definition instead of the declaration.
1773 llvm::Constant *C = nullptr;
1774 if (Var->getInit()) {
1775 const APValue *Value = Var->evaluateValue();
1776 if (Value) {
1777 if (Value->isInt())
1778 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1779 if (Value->isFloat())
1780 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1781 }
1782 }
1783
1784 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1785 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
1786 ? llvm::dwarf::DW_TAG_variable
1787 : llvm::dwarf::DW_TAG_member;
1788 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1789 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1790 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
1791 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1792 return GV;
1793}
1794
1795void CGDebugInfo::CollectRecordNormalField(
1796 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1797 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1798 const RecordDecl *RD) {
1799 StringRef name = field->getName();
1800 QualType type = field->getType();
1801
1802 // Ignore unnamed fields unless they're anonymous structs/unions.
1803 if (name.empty() && !type->isRecordType())
1804 return;
1805
1806 llvm::DIType *FieldType;
1807 if (field->isBitField()) {
1808 llvm::DIDerivedType *BitFieldType;
1809 FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
1810 if (llvm::DIType *Separator =
1811 createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
1812 elements.push_back(Separator);
1813 } else {
1814 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1815 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1816 FieldType =
1817 createFieldType(name, type, field->getLocation(), field->getAccess(),
1818 OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1819 }
1820
1821 elements.push_back(FieldType);
1822}
1823
1824void CGDebugInfo::CollectRecordNestedType(
1825 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1826 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1827 // Injected class names are not considered nested records.
1828 if (isa<InjectedClassNameType>(Ty))
1829 return;
1831 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1832 elements.push_back(nestedType);
1833}
1834
1835void CGDebugInfo::CollectRecordFields(
1836 const RecordDecl *record, llvm::DIFile *tunit,
1838 llvm::DICompositeType *RecordTy) {
1839 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1840
1841 if (CXXDecl && CXXDecl->isLambda())
1842 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1843 else {
1844 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1845
1846 // Field number for non-static fields.
1847 unsigned fieldNo = 0;
1848
1849 // Static and non-static members should appear in the same order as
1850 // the corresponding declarations in the source program.
1851 for (const auto *I : record->decls())
1852 if (const auto *V = dyn_cast<VarDecl>(I)) {
1853 if (V->hasAttr<NoDebugAttr>())
1854 continue;
1855
1856 // Skip variable template specializations when emitting CodeView. MSVC
1857 // doesn't emit them.
1858 if (CGM.getCodeGenOpts().EmitCodeView &&
1859 isa<VarTemplateSpecializationDecl>(V))
1860 continue;
1861
1862 if (isa<VarTemplatePartialSpecializationDecl>(V))
1863 continue;
1864
1865 // Reuse the existing static member declaration if one exists
1866 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1867 if (MI != StaticDataMemberCache.end()) {
1868 assert(MI->second &&
1869 "Static data member declaration should still exist");
1870 elements.push_back(MI->second);
1871 } else {
1872 auto Field = CreateRecordStaticField(V, RecordTy, record);
1873 elements.push_back(Field);
1874 }
1875 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1876 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1877 elements, RecordTy, record);
1878
1879 // Bump field number for next field.
1880 ++fieldNo;
1881 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1882 // Debug info for nested types is included in the member list only for
1883 // CodeView.
1884 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
1885 // MSVC doesn't generate nested type for anonymous struct/union.
1886 if (isa<RecordDecl>(I) &&
1887 cast<RecordDecl>(I)->isAnonymousStructOrUnion())
1888 continue;
1889 if (!nestedType->isImplicit() &&
1890 nestedType->getDeclContext() == record)
1891 CollectRecordNestedType(nestedType, elements);
1892 }
1893 }
1894 }
1895}
1896
1897llvm::DISubroutineType *
1898CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1899 llvm::DIFile *Unit) {
1900 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1901 if (Method->isStatic())
1902 return cast_or_null<llvm::DISubroutineType>(
1903 getOrCreateType(QualType(Func, 0), Unit));
1904 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
1905}
1906
1907llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1908 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1909 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1910 Qualifiers &Qc = EPI.TypeQuals;
1911 Qc.removeConst();
1912 Qc.removeVolatile();
1913 Qc.removeRestrict();
1914 Qc.removeUnaligned();
1915 // Keep the removed qualifiers in sync with
1916 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1917 // On a 'real' member function type, these qualifiers are carried on the type
1918 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1919 // tags around them. (But, in the raw function types with qualifiers, they have
1920 // to use wrapper types.)
1921
1922 // Add "this" pointer.
1923 const auto *OriginalFunc = cast<llvm::DISubroutineType>(
1924 getOrCreateType(CGM.getContext().getFunctionType(
1925 Func->getReturnType(), Func->getParamTypes(), EPI),
1926 Unit));
1927 llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
1928 assert(Args.size() && "Invalid number of arguments!");
1929
1931
1932 // First element is always return type. For 'void' functions it is NULL.
1933 Elts.push_back(Args[0]);
1934
1935 // "this" pointer is always first argument.
1936 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1937 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1938 // Create pointer type directly in this case.
1939 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1940 uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy);
1941 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1942 llvm::DIType *PointeeType =
1943 getOrCreateType(ThisPtrTy->getPointeeType(), Unit);
1944 llvm::DIType *ThisPtrType =
1945 DBuilder.createPointerType(PointeeType, Size, Align);
1946 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1947 // TODO: This and the artificial type below are misleading, the
1948 // types aren't artificial the argument is, but the current
1949 // metadata doesn't represent that.
1950 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1951 Elts.push_back(ThisPtrType);
1952 } else {
1953 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1954 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1955 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1956 Elts.push_back(ThisPtrType);
1957 }
1958
1959 // Copy rest of the arguments.
1960 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1961 Elts.push_back(Args[i]);
1962
1963 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1964
1965 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
1966 getDwarfCC(Func->getCallConv()));
1967}
1968
1969/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1970/// inside a function.
1971static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1972 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1973 return isFunctionLocalClass(NRD);
1974 if (isa<FunctionDecl>(RD->getDeclContext()))
1975 return true;
1976 return false;
1977}
1978
1979llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1980 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1981 bool IsCtorOrDtor =
1982 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1983
1984 StringRef MethodName = getFunctionName(Method);
1985 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1986
1987 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1988 // make sense to give a single ctor/dtor a linkage name.
1989 StringRef MethodLinkageName;
1990 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1991 // property to use here. It may've been intended to model "is non-external
1992 // type" but misses cases of non-function-local but non-external classes such
1993 // as those in anonymous namespaces as well as the reverse - external types
1994 // that are function local, such as those in (non-local) inline functions.
1995 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1996 MethodLinkageName = CGM.getMangledName(Method);
1997
1998 // Get the location for the method.
1999 llvm::DIFile *MethodDefUnit = nullptr;
2000 unsigned MethodLine = 0;
2001 if (!Method->isImplicit()) {
2002 MethodDefUnit = getOrCreateFile(Method->getLocation());
2003 MethodLine = getLineNumber(Method->getLocation());
2004 }
2005
2006 // Collect virtual method info.
2007 llvm::DIType *ContainingType = nullptr;
2008 unsigned VIndex = 0;
2009 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2010 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2011 int ThisAdjustment = 0;
2012
2014 if (Method->isPureVirtual())
2015 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2016 else
2017 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2018
2019 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2020 // It doesn't make sense to give a virtual destructor a vtable index,
2021 // since a single destructor has two entries in the vtable.
2022 if (!isa<CXXDestructorDecl>(Method))
2023 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2024 } else {
2025 // Emit MS ABI vftable information. There is only one entry for the
2026 // deleting dtor.
2027 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2028 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
2031 VIndex = ML.Index;
2032
2033 // CodeView only records the vftable offset in the class that introduces
2034 // the virtual method. This is possible because, unlike Itanium, the MS
2035 // C++ ABI does not include all virtual methods from non-primary bases in
2036 // the vtable for the most derived class. For example, if C inherits from
2037 // A and B, C's primary vftable will not include B's virtual methods.
2038 if (Method->size_overridden_methods() == 0)
2039 Flags |= llvm::DINode::FlagIntroducedVirtual;
2040
2041 // The 'this' adjustment accounts for both the virtual and non-virtual
2042 // portions of the adjustment. Presumably the debugger only uses it when
2043 // it knows the dynamic type of an object.
2046 .getQuantity();
2047 }
2048 ContainingType = RecordTy;
2049 }
2050
2051 if (Method->getCanonicalDecl()->isDeleted())
2052 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2053
2054 if (Method->isNoReturn())
2055 Flags |= llvm::DINode::FlagNoReturn;
2056
2057 if (Method->isStatic())
2058 Flags |= llvm::DINode::FlagStaticMember;
2059 if (Method->isImplicit())
2060 Flags |= llvm::DINode::FlagArtificial;
2061 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2062 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2063 if (CXXC->isExplicit())
2064 Flags |= llvm::DINode::FlagExplicit;
2065 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2066 if (CXXC->isExplicit())
2067 Flags |= llvm::DINode::FlagExplicit;
2068 }
2069 if (Method->hasPrototype())
2070 Flags |= llvm::DINode::FlagPrototyped;
2071 if (Method->getRefQualifier() == RQ_LValue)
2072 Flags |= llvm::DINode::FlagLValueReference;
2073 if (Method->getRefQualifier() == RQ_RValue)
2074 Flags |= llvm::DINode::FlagRValueReference;
2075 if (!Method->isExternallyVisible())
2076 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2077 if (CGM.getLangOpts().Optimize)
2078 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2079
2080 // In this debug mode, emit type info for a class when its constructor type
2081 // info is emitted.
2082 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2083 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2084 completeUnusedClass(*CD->getParent());
2085
2086 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2087 llvm::DISubprogram *SP = DBuilder.createMethod(
2088 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2089 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2090 TParamsArray.get());
2091
2092 SPCache[Method->getCanonicalDecl()].reset(SP);
2093
2094 return SP;
2095}
2096
2097void CGDebugInfo::CollectCXXMemberFunctions(
2098 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2099 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2100
2101 // Since we want more than just the individual member decls if we
2102 // have templated functions iterate over every declaration to gather
2103 // the functions.
2104 for (const auto *I : RD->decls()) {
2105 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2106 // If the member is implicit, don't add it to the member list. This avoids
2107 // the member being added to type units by LLVM, while still allowing it
2108 // to be emitted into the type declaration/reference inside the compile
2109 // unit.
2110 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2111 // FIXME: Handle Using(Shadow?)Decls here to create
2112 // DW_TAG_imported_declarations inside the class for base decls brought into
2113 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2114 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2115 // referenced)
2116 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2117 continue;
2118
2120 continue;
2121
2122 // Reuse the existing member function declaration if it exists.
2123 // It may be associated with the declaration of the type & should be
2124 // reused as we're building the definition.
2125 //
2126 // This situation can arise in the vtable-based debug info reduction where
2127 // implicit members are emitted in a non-vtable TU.
2128 auto MI = SPCache.find(Method->getCanonicalDecl());
2129 EltTys.push_back(MI == SPCache.end()
2130 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2131 : static_cast<llvm::Metadata *>(MI->second));
2132 }
2133}
2134
2135void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2137 llvm::DIType *RecordTy) {
2139 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2140 llvm::DINode::FlagZero);
2141
2142 // If we are generating CodeView debug info, we also need to emit records for
2143 // indirect virtual base classes.
2144 if (CGM.getCodeGenOpts().EmitCodeView) {
2145 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2146 llvm::DINode::FlagIndirectVirtualBase);
2147 }
2148}
2149
2150void CGDebugInfo::CollectCXXBasesAux(
2151 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2152 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2155 llvm::DINode::DIFlags StartingFlags) {
2156 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2157 for (const auto &BI : Bases) {
2158 const auto *Base =
2159 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
2160 if (!SeenTypes.insert(Base).second)
2161 continue;
2162 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2163 llvm::DINode::DIFlags BFlags = StartingFlags;
2164 uint64_t BaseOffset;
2165 uint32_t VBPtrOffset = 0;
2166
2167 if (BI.isVirtual()) {
2168 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2169 // virtual base offset offset is -ve. The code generator emits dwarf
2170 // expression where it expects +ve number.
2171 BaseOffset = 0 - CGM.getItaniumVTableContext()
2173 .getQuantity();
2174 } else {
2175 // In the MS ABI, store the vbtable offset, which is analogous to the
2176 // vbase offset offset in Itanium.
2177 BaseOffset =
2179 VBPtrOffset = CGM.getContext()
2182 .getQuantity();
2183 }
2184 BFlags |= llvm::DINode::FlagVirtual;
2185 } else
2186 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2187 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2188 // BI->isVirtual() and bits when not.
2189
2190 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2191 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2192 VBPtrOffset, BFlags);
2193 EltTys.push_back(DTy);
2194 }
2195}
2196
2197llvm::DINodeArray
2198CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2199 llvm::DIFile *Unit) {
2200 if (!OArgs)
2201 return llvm::DINodeArray();
2202 TemplateArgs &Args = *OArgs;
2203 SmallVector<llvm::Metadata *, 16> TemplateParams;
2204 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2205 const TemplateArgument &TA = Args.Args[i];
2206 StringRef Name;
2207 const bool defaultParameter = TA.getIsDefaulted();
2208 if (Args.TList)
2209 Name = Args.TList->getParam(i)->getName();
2210
2211 switch (TA.getKind()) {
2213 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2214 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2215 TheCU, Name, TTy, defaultParameter));
2216
2217 } break;
2219 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2220 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2221 TheCU, Name, TTy, defaultParameter,
2222 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2223 } break;
2225 const ValueDecl *D = TA.getAsDecl();
2227 llvm::DIType *TTy = getOrCreateType(T, Unit);
2228 llvm::Constant *V = nullptr;
2229 // Skip retrieve the value if that template parameter has cuda device
2230 // attribute, i.e. that value is not available at the host side.
2231 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2232 !D->hasAttr<CUDADeviceAttr>()) {
2233 // Variable pointer template parameters have a value that is the address
2234 // of the variable.
2235 if (const auto *VD = dyn_cast<VarDecl>(D))
2236 V = CGM.GetAddrOfGlobalVar(VD);
2237 // Member function pointers have special support for building them,
2238 // though this is currently unsupported in LLVM CodeGen.
2239 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2240 MD && MD->isImplicitObjectMemberFunction())
2242 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2243 V = CGM.GetAddrOfFunction(FD);
2244 // Member data pointers have special handling too to compute the fixed
2245 // offset within the object.
2246 else if (const auto *MPT =
2247 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2248 // These five lines (& possibly the above member function pointer
2249 // handling) might be able to be refactored to use similar code in
2250 // CodeGenModule::getMemberPointerConstant
2251 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2252 CharUnits chars =
2253 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2254 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2255 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2256 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2257 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2258 if (T->isRecordType())
2260 SourceLocation(), TPO->getValue(), TPO->getType());
2261 else
2263 }
2264 assert(V && "Failed to find template parameter pointer");
2265 V = V->stripPointerCasts();
2266 }
2267 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2268 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2269 } break;
2271 QualType T = TA.getNullPtrType();
2272 llvm::DIType *TTy = getOrCreateType(T, Unit);
2273 llvm::Constant *V = nullptr;
2274 // Special case member data pointer null values since they're actually -1
2275 // instead of zero.
2276 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2277 // But treat member function pointers as simple zero integers because
2278 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2279 // CodeGen grows handling for values of non-null member function
2280 // pointers then perhaps we could remove this special case and rely on
2281 // EmitNullMemberPointer for member function pointers.
2282 if (MPT->isMemberDataPointer())
2283 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2284 if (!V)
2285 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2286 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2287 TheCU, Name, TTy, defaultParameter, V));
2288 } break;
2291 llvm::DIType *TTy = getOrCreateType(T, Unit);
2292 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2294 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2295 TheCU, Name, TTy, defaultParameter, V));
2296 } break;
2298 std::string QualName;
2299 llvm::raw_string_ostream OS(QualName);
2301 OS, getPrintingPolicy());
2302 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2303 TheCU, Name, nullptr, OS.str(), defaultParameter));
2304 break;
2305 }
2307 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2308 TheCU, Name, nullptr,
2309 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2310 break;
2312 const Expr *E = TA.getAsExpr();
2313 QualType T = E->getType();
2314 if (E->isGLValue())
2316 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2317 assert(V && "Expression in template argument isn't constant");
2318 llvm::DIType *TTy = getOrCreateType(T, Unit);
2319 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2320 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2321 } break;
2322 // And the following should never occur:
2325 llvm_unreachable(
2326 "These argument types shouldn't exist in concrete types");
2327 }
2328 }
2329 return DBuilder.getOrCreateArray(TemplateParams);
2330}
2331
2332std::optional<CGDebugInfo::TemplateArgs>
2333CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2334 if (FD->getTemplatedKind() ==
2337 ->getTemplate()
2339 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2340 }
2341 return std::nullopt;
2342}
2343std::optional<CGDebugInfo::TemplateArgs>
2344CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2345 // Always get the full list of parameters, not just the ones from the
2346 // specialization. A partial specialization may have fewer parameters than
2347 // there are arguments.
2348 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2349 if (!TS)
2350 return std::nullopt;
2351 VarTemplateDecl *T = TS->getSpecializedTemplate();
2352 const TemplateParameterList *TList = T->getTemplateParameters();
2353 auto TA = TS->getTemplateArgs().asArray();
2354 return {{TList, TA}};
2355}
2356std::optional<CGDebugInfo::TemplateArgs>
2357CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2358 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2359 // Always get the full list of parameters, not just the ones from the
2360 // specialization. A partial specialization may have fewer parameters than
2361 // there are arguments.
2362 TemplateParameterList *TPList =
2363 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2364 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2365 return {{TPList, TAList.asArray()}};
2366 }
2367 return std::nullopt;
2368}
2369
2370llvm::DINodeArray
2371CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2372 llvm::DIFile *Unit) {
2373 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2374}
2375
2376llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2377 llvm::DIFile *Unit) {
2378 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2379}
2380
2381llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2382 llvm::DIFile *Unit) {
2383 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2384}
2385
2386llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2387 if (!D->hasAttr<BTFDeclTagAttr>())
2388 return nullptr;
2389
2391 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2392 llvm::Metadata *Ops[2] = {
2393 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2394 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2395 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2396 }
2397 return DBuilder.getOrCreateArray(Annotations);
2398}
2399
2400llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2401 if (VTablePtrType)
2402 return VTablePtrType;
2403
2404 ASTContext &Context = CGM.getContext();
2405
2406 /* Function type */
2407 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2408 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2409 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2410 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2411 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2412 std::optional<unsigned> DWARFAddressSpace =
2413 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2414
2415 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2416 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2417 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2418 return VTablePtrType;
2419}
2420
2421StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2422 // Copy the gdb compatible name on the side and use its reference.
2423 return internString("_vptr$", RD->getNameAsString());
2424}
2425
2426StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2427 DynamicInitKind StubKind,
2428 llvm::Function *InitFn) {
2429 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2430 // arbitrary.
2431 if (!CGM.getCodeGenOpts().EmitCodeView ||
2433 return InitFn->getName();
2434
2435 // Print the normal qualified name for the variable, then break off the last
2436 // NNS, and add the appropriate other text. Clang always prints the global
2437 // variable name without template arguments, so we can use rsplit("::") and
2438 // then recombine the pieces.
2439 SmallString<128> QualifiedGV;
2440 StringRef Quals;
2441 StringRef GVName;
2442 {
2443 llvm::raw_svector_ostream OS(QualifiedGV);
2444 VD->printQualifiedName(OS, getPrintingPolicy());
2445 std::tie(Quals, GVName) = OS.str().rsplit("::");
2446 if (GVName.empty())
2447 std::swap(Quals, GVName);
2448 }
2449
2450 SmallString<128> InitName;
2451 llvm::raw_svector_ostream OS(InitName);
2452 if (!Quals.empty())
2453 OS << Quals << "::";
2454
2455 switch (StubKind) {
2458 llvm_unreachable("not an initializer");
2460 OS << "`dynamic initializer for '";
2461 break;
2463 OS << "`dynamic atexit destructor for '";
2464 break;
2465 }
2466
2467 OS << GVName;
2468
2469 // Add any template specialization args.
2470 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2471 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2472 getPrintingPolicy());
2473 }
2474
2475 OS << '\'';
2476
2477 return internString(OS.str());
2478}
2479
2480void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2482 // If this class is not dynamic then there is not any vtable info to collect.
2483 if (!RD->isDynamicClass())
2484 return;
2485
2486 // Don't emit any vtable shape or vptr info if this class doesn't have an
2487 // extendable vfptr. This can happen if the class doesn't have virtual
2488 // methods, or in the MS ABI if those virtual methods only come from virtually
2489 // inherited bases.
2490 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2491 if (!RL.hasExtendableVFPtr())
2492 return;
2493
2494 // CodeView needs to know how large the vtable of every dynamic class is, so
2495 // emit a special named pointer type into the element list. The vptr type
2496 // points to this type as well.
2497 llvm::DIType *VPtrTy = nullptr;
2498 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2500 if (NeedVTableShape) {
2501 uint64_t PtrWidth =
2503 const VTableLayout &VFTLayout =
2505 unsigned VSlotCount =
2506 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2507 unsigned VTableWidth = PtrWidth * VSlotCount;
2508 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2509 std::optional<unsigned> DWARFAddressSpace =
2510 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2511
2512 // Create a very wide void* type and insert it directly in the element list.
2513 llvm::DIType *VTableType = DBuilder.createPointerType(
2514 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2515 EltTys.push_back(VTableType);
2516
2517 // The vptr is a pointer to this special vtable type.
2518 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2519 }
2520
2521 // If there is a primary base then the artificial vptr member lives there.
2522 if (RL.getPrimaryBase())
2523 return;
2524
2525 if (!VPtrTy)
2526 VPtrTy = getOrCreateVTablePtrType(Unit);
2527
2528 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2529 llvm::DIType *VPtrMember =
2530 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2531 llvm::DINode::FlagArtificial, VPtrTy);
2532 EltTys.push_back(VPtrMember);
2533}
2534
2537 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2538 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2539 return T;
2540}
2541
2544 return getOrCreateStandaloneType(D, Loc);
2545}
2546
2549 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2550 assert(!D.isNull() && "null type");
2551 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2552 assert(T && "could not create debug info for type");
2553
2554 RetainedTypes.push_back(D.getAsOpaquePtr());
2555 return T;
2556}
2557
2559 QualType AllocatedTy,
2561 if (CGM.getCodeGenOpts().getDebugInfo() <=
2562 llvm::codegenoptions::DebugLineTablesOnly)
2563 return;
2564 llvm::MDNode *node;
2565 if (AllocatedTy->isVoidType())
2566 node = llvm::MDNode::get(CGM.getLLVMContext(), std::nullopt);
2567 else
2568 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2569
2570 CI->setMetadata("heapallocsite", node);
2571}
2572
2574 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2575 return;
2576 QualType Ty = CGM.getContext().getEnumType(ED);
2577 void *TyPtr = Ty.getAsOpaquePtr();
2578 auto I = TypeCache.find(TyPtr);
2579 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2580 return;
2581 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2582 assert(!Res->isForwardDecl());
2583 TypeCache[TyPtr].reset(Res);
2584}
2585
2587 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2588 !CGM.getLangOpts().CPlusPlus)
2590}
2591
2592/// Return true if the class or any of its methods are marked dllimport.
2594 if (RD->hasAttr<DLLImportAttr>())
2595 return true;
2596 for (const CXXMethodDecl *MD : RD->methods())
2597 if (MD->hasAttr<DLLImportAttr>())
2598 return true;
2599 return false;
2600}
2601
2602/// Does a type definition exist in an imported clang module?
2603static bool isDefinedInClangModule(const RecordDecl *RD) {
2604 // Only definitions that where imported from an AST file come from a module.
2605 if (!RD || !RD->isFromASTFile())
2606 return false;
2607 // Anonymous entities cannot be addressed. Treat them as not from module.
2608 if (!RD->isExternallyVisible() && RD->getName().empty())
2609 return false;
2610 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2611 if (!CXXDecl->isCompleteDefinition())
2612 return false;
2613 // Check wether RD is a template.
2614 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2615 if (TemplateKind != TSK_Undeclared) {
2616 // Unfortunately getOwningModule() isn't accurate enough to find the
2617 // owning module of a ClassTemplateSpecializationDecl that is inside a
2618 // namespace spanning multiple modules.
2619 bool Explicit = false;
2620 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2621 Explicit = TD->isExplicitInstantiationOrSpecialization();
2622 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2623 return false;
2624 // This is a template, check the origin of the first member.
2625 if (CXXDecl->field_begin() == CXXDecl->field_end())
2626 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2627 if (!CXXDecl->field_begin()->isFromASTFile())
2628 return false;
2629 }
2630 }
2631 return true;
2632}
2633
2635 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2636 if (CXXRD->isDynamicClass() &&
2637 CGM.getVTableLinkage(CXXRD) ==
2638 llvm::GlobalValue::AvailableExternallyLinkage &&
2640 return;
2641
2642 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2643 return;
2644
2645 completeClass(RD);
2646}
2647
2649 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2650 return;
2651 QualType Ty = CGM.getContext().getRecordType(RD);
2652 void *TyPtr = Ty.getAsOpaquePtr();
2653 auto I = TypeCache.find(TyPtr);
2654 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2655 return;
2656
2657 // We want the canonical definition of the structure to not
2658 // be the typedef. Since that would lead to circular typedef
2659 // metadata.
2660 auto [Res, PrefRes] = CreateTypeDefinition(Ty->castAs<RecordType>());
2661 assert(!Res->isForwardDecl());
2662 TypeCache[TyPtr].reset(Res);
2663}
2664
2667 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2669 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2670 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2671 return true;
2672 return false;
2673}
2674
2675static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2676 // Constructor homing can be used for classes that cannnot be constructed
2677 // without emitting code for one of their constructors. This is classes that
2678 // don't have trivial or constexpr constructors, or can be created from
2679 // aggregate initialization. Also skip lambda objects because they don't call
2680 // constructors.
2681
2682 // Skip this optimization if the class or any of its methods are marked
2683 // dllimport.
2685 return false;
2686
2687 if (RD->isLambda() || RD->isAggregate() ||
2690 return false;
2691
2692 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
2693 if (Ctor->isCopyOrMoveConstructor())
2694 continue;
2695 if (!Ctor->isDeleted())
2696 return true;
2697 }
2698 return false;
2699}
2700
2701static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
2702 bool DebugTypeExtRefs, const RecordDecl *RD,
2703 const LangOptions &LangOpts) {
2704 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2705 return true;
2706
2707 if (auto *ES = RD->getASTContext().getExternalSource())
2708 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2709 return true;
2710
2711 // Only emit forward declarations in line tables only to keep debug info size
2712 // small. This only applies to CodeView, since we don't emit types in DWARF
2713 // line tables only.
2714 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
2715 return true;
2716
2717 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2718 RD->hasAttr<StandaloneDebugAttr>())
2719 return false;
2720
2721 if (!LangOpts.CPlusPlus)
2722 return false;
2723
2725 return true;
2726
2727 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2728
2729 if (!CXXDecl)
2730 return false;
2731
2732 // Only emit complete debug info for a dynamic class when its vtable is
2733 // emitted. However, Microsoft debuggers don't resolve type information
2734 // across DLL boundaries, so skip this optimization if the class or any of its
2735 // methods are marked dllimport. This isn't a complete solution, since objects
2736 // without any dllimport methods can be used in one DLL and constructed in
2737 // another, but it is the current behavior of LimitedDebugInfo.
2738 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2739 !isClassOrMethodDLLImport(CXXDecl))
2740 return true;
2741
2743 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2744 Spec = SD->getSpecializationKind();
2745
2748 CXXDecl->method_end()))
2749 return true;
2750
2751 // In constructor homing mode, only emit complete debug info for a class
2752 // when its constructor is emitted.
2753 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
2754 canUseCtorHoming(CXXDecl))
2755 return true;
2756
2757 return false;
2758}
2759
2761 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2762 return;
2763
2764 QualType Ty = CGM.getContext().getRecordType(RD);
2765 llvm::DIType *T = getTypeOrNull(Ty);
2766 if (T && T->isForwardDecl())
2768}
2769
2770llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2771 RecordDecl *RD = Ty->getDecl();
2772 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2773 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2774 CGM.getLangOpts())) {
2775 if (!T)
2776 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2777 return T;
2778 }
2779
2780 auto [Def, Pref] = CreateTypeDefinition(Ty);
2781
2782 return Pref ? Pref : Def;
2783}
2784
2785llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
2786 llvm::DIFile *Unit) {
2787 if (!RD)
2788 return nullptr;
2789
2790 auto const *PNA = RD->getAttr<PreferredNameAttr>();
2791 if (!PNA)
2792 return nullptr;
2793
2794 return getOrCreateType(PNA->getTypedefType(), Unit);
2795}
2796
2797std::pair<llvm::DIType *, llvm::DIType *>
2798CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2799 RecordDecl *RD = Ty->getDecl();
2800
2801 // Get overall information about the record type for the debug info.
2802 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2803
2804 // Records and classes and unions can all be recursive. To handle them, we
2805 // first generate a debug descriptor for the struct as a forward declaration.
2806 // Then (if it is a definition) we go through and get debug info for all of
2807 // its members. Finally, we create a descriptor for the complete type (which
2808 // may refer to the forward decl if the struct is recursive) and replace all
2809 // uses of the forward declaration with the final definition.
2810 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2811
2812 const RecordDecl *D = RD->getDefinition();
2813 if (!D || !D->isCompleteDefinition())
2814 return {FwdDecl, nullptr};
2815
2816 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2817 CollectContainingType(CXXDecl, FwdDecl);
2818
2819 // Push the struct on region stack.
2820 LexicalBlockStack.emplace_back(&*FwdDecl);
2821 RegionMap[Ty->getDecl()].reset(FwdDecl);
2822
2823 // Convert all the elements.
2825 // what about nested types?
2826
2827 // Note: The split of CXXDecl information here is intentional, the
2828 // gdb tests will depend on a certain ordering at printout. The debug
2829 // information offsets are still correct if we merge them all together
2830 // though.
2831 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2832 if (CXXDecl) {
2833 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2834 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2835 }
2836
2837 // Collect data fields (including static variables and any initializers).
2838 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2839 if (CXXDecl)
2840 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2841
2842 LexicalBlockStack.pop_back();
2843 RegionMap.erase(Ty->getDecl());
2844
2845 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2846 DBuilder.replaceArrays(FwdDecl, Elements);
2847
2848 if (FwdDecl->isTemporary())
2849 FwdDecl =
2850 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2851
2852 RegionMap[Ty->getDecl()].reset(FwdDecl);
2853
2854 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
2855 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
2856 return {FwdDecl, PrefDI};
2857
2858 return {FwdDecl, nullptr};
2859}
2860
2861llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2862 llvm::DIFile *Unit) {
2863 // Ignore protocols.
2864 return getOrCreateType(Ty->getBaseType(), Unit);
2865}
2866
2867llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2868 llvm::DIFile *Unit) {
2869 // Ignore protocols.
2871
2872 // Use Typedefs to represent ObjCTypeParamType.
2873 return DBuilder.createTypedef(
2874 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2875 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2876 getDeclContextDescriptor(Ty->getDecl()));
2877}
2878
2879/// \return true if Getter has the default name for the property PD.
2881 const ObjCMethodDecl *Getter) {
2882 assert(PD);
2883 if (!Getter)
2884 return true;
2885
2886 assert(Getter->getDeclName().isObjCZeroArgSelector());
2887 return PD->getName() ==
2889}
2890
2891/// \return true if Setter has the default name for the property PD.
2893 const ObjCMethodDecl *Setter) {
2894 assert(PD);
2895 if (!Setter)
2896 return true;
2897
2898 assert(Setter->getDeclName().isObjCOneArgSelector());
2901}
2902
2903llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2904 llvm::DIFile *Unit) {
2905 ObjCInterfaceDecl *ID = Ty->getDecl();
2906 if (!ID)
2907 return nullptr;
2908
2909 // Return a forward declaration if this type was imported from a clang module,
2910 // and this is not the compile unit with the implementation of the type (which
2911 // may contain hidden ivars).
2912 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2913 !ID->getImplementation())
2914 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2915 ID->getName(),
2916 getDeclContextDescriptor(ID), Unit, 0);
2917
2918 // Get overall information about the record type for the debug info.
2919 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2920 unsigned Line = getLineNumber(ID->getLocation());
2921 auto RuntimeLang =
2922 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2923
2924 // If this is just a forward declaration return a special forward-declaration
2925 // debug type since we won't be able to lay out the entire type.
2926 ObjCInterfaceDecl *Def = ID->getDefinition();
2927 if (!Def || !Def->getImplementation()) {
2928 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2929 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2930 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2931 DefUnit, Line, RuntimeLang);
2932 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2933 return FwdDecl;
2934 }
2935
2936 return CreateTypeDefinition(Ty, Unit);
2937}
2938
2939llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2940 bool CreateSkeletonCU) {
2941 // Use the Module pointer as the key into the cache. This is a
2942 // nullptr if the "Module" is a PCH, which is safe because we don't
2943 // support chained PCH debug info, so there can only be a single PCH.
2944 const Module *M = Mod.getModuleOrNull();
2945 auto ModRef = ModuleCache.find(M);
2946 if (ModRef != ModuleCache.end())
2947 return cast<llvm::DIModule>(ModRef->second);
2948
2949 // Macro definitions that were defined with "-D" on the command line.
2950 SmallString<128> ConfigMacros;
2951 {
2952 llvm::raw_svector_ostream OS(ConfigMacros);
2953 const auto &PPOpts = CGM.getPreprocessorOpts();
2954 unsigned I = 0;
2955 // Translate the macro definitions back into a command line.
2956 for (auto &M : PPOpts.Macros) {
2957 if (++I > 1)
2958 OS << " ";
2959 const std::string &Macro = M.first;
2960 bool Undef = M.second;
2961 OS << "\"-" << (Undef ? 'U' : 'D');
2962 for (char c : Macro)
2963 switch (c) {
2964 case '\\':
2965 OS << "\\\\";
2966 break;
2967 case '"':
2968 OS << "\\\"";
2969 break;
2970 default:
2971 OS << c;
2972 }
2973 OS << '\"';
2974 }
2975 }
2976
2977 bool IsRootModule = M ? !M->Parent : true;
2978 // When a module name is specified as -fmodule-name, that module gets a
2979 // clang::Module object, but it won't actually be built or imported; it will
2980 // be textual.
2981 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2982 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
2983 "clang module without ASTFile must be specified by -fmodule-name");
2984
2985 // Return a StringRef to the remapped Path.
2986 auto RemapPath = [this](StringRef Path) -> std::string {
2987 std::string Remapped = remapDIPath(Path);
2988 StringRef Relative(Remapped);
2989 StringRef CompDir = TheCU->getDirectory();
2990 if (Relative.consume_front(CompDir))
2991 Relative.consume_front(llvm::sys::path::get_separator());
2992
2993 return Relative.str();
2994 };
2995
2996 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2997 // PCH files don't have a signature field in the control block,
2998 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2999 // We use the lower 64 bits for debug info.
3000
3001 uint64_t Signature = 0;
3002 if (const auto &ModSig = Mod.getSignature())
3003 Signature = ModSig.truncatedValue();
3004 else
3005 Signature = ~1ULL;
3006
3007 llvm::DIBuilder DIB(CGM.getModule());
3008 SmallString<0> PCM;
3009 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3011 PCM = getCurrentDirname();
3012 else
3013 PCM = Mod.getPath();
3014 }
3015 llvm::sys::path::append(PCM, Mod.getASTFile());
3016 DIB.createCompileUnit(
3017 TheCU->getSourceLanguage(),
3018 // TODO: Support "Source" from external AST providers?
3019 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3020 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3021 llvm::DICompileUnit::FullDebug, Signature);
3022 DIB.finalize();
3023 }
3024
3025 llvm::DIModule *Parent =
3026 IsRootModule ? nullptr
3027 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3028 CreateSkeletonCU);
3029 std::string IncludePath = Mod.getPath().str();
3030 llvm::DIModule *DIMod =
3031 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3032 RemapPath(IncludePath));
3033 ModuleCache[M].reset(DIMod);
3034 return DIMod;
3035}
3036
3037llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3038 llvm::DIFile *Unit) {
3039 ObjCInterfaceDecl *ID = Ty->getDecl();
3040 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3041 unsigned Line = getLineNumber(ID->getLocation());
3042 unsigned RuntimeLang = TheCU->getSourceLanguage();
3043
3044 // Bit size, align and offset of the type.
3045 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3046 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3047
3048 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3049 if (ID->getImplementation())
3050 Flags |= llvm::DINode::FlagObjcClassComplete;
3051
3052 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3053 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3054 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3055 nullptr, llvm::DINodeArray(), RuntimeLang);
3056
3057 QualType QTy(Ty, 0);
3058 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3059
3060 // Push the struct on region stack.
3061 LexicalBlockStack.emplace_back(RealDecl);
3062 RegionMap[Ty->getDecl()].reset(RealDecl);
3063
3064 // Convert all the elements.
3066
3067 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3068 if (SClass) {
3069 llvm::DIType *SClassTy =
3070 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3071 if (!SClassTy)
3072 return nullptr;
3073
3074 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3075 llvm::DINode::FlagZero);
3076 EltTys.push_back(InhTag);
3077 }
3078
3079 // Create entries for all of the properties.
3080 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3081 SourceLocation Loc = PD->getLocation();
3082 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3083 unsigned PLine = getLineNumber(Loc);
3084 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3085 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3086 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3087 PD->getName(), PUnit, PLine,
3088 hasDefaultGetterName(PD, Getter) ? ""
3089 : getSelectorName(PD->getGetterName()),
3090 hasDefaultSetterName(PD, Setter) ? ""
3091 : getSelectorName(PD->getSetterName()),
3092 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3093 EltTys.push_back(PropertyNode);
3094 };
3095 {
3096 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3097 // empty/tombstone keys in the data type (and bool is too small for that).
3098 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3099 /// List of already emitted properties. Two distinct class and instance
3100 /// properties can share the same identifier (but not two instance
3101 /// properties or two class properties).
3103 /// Returns the IsClassAndIdent key for the given property.
3104 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3105 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3106 };
3107 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3108 for (auto *PD : ClassExt->properties()) {
3109 PropertySet.insert(GetIsClassAndIdent(PD));
3110 AddProperty(PD);
3111 }
3112 for (const auto *PD : ID->properties()) {
3113 // Don't emit duplicate metadata for properties that were already in a
3114 // class extension.
3115 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3116 continue;
3117 AddProperty(PD);
3118 }
3119 }
3120
3122 unsigned FieldNo = 0;
3123 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3124 Field = Field->getNextIvar(), ++FieldNo) {
3125 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3126 if (!FieldTy)
3127 return nullptr;
3128
3129 StringRef FieldName = Field->getName();
3130
3131 // Ignore unnamed fields.
3132 if (FieldName.empty())
3133 continue;
3134
3135 // Get the location for the field.
3136 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3137 unsigned FieldLine = getLineNumber(Field->getLocation());
3138 QualType FType = Field->getType();
3139 uint64_t FieldSize = 0;
3140 uint32_t FieldAlign = 0;
3141
3142 if (!FType->isIncompleteArrayType()) {
3143
3144 // Bit size, align and offset of the type.
3145 FieldSize = Field->isBitField()
3146 ? Field->getBitWidthValue(CGM.getContext())
3147 : CGM.getContext().getTypeSize(FType);
3148 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3149 }
3150
3151 uint64_t FieldOffset;
3152 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3153 // We don't know the runtime offset of an ivar if we're using the
3154 // non-fragile ABI. For bitfields, use the bit offset into the first
3155 // byte of storage of the bitfield. For other fields, use zero.
3156 if (Field->isBitField()) {
3157 FieldOffset =
3158 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3159 FieldOffset %= CGM.getContext().getCharWidth();
3160 } else {
3161 FieldOffset = 0;
3162 }
3163 } else {
3164 FieldOffset = RL.getFieldOffset(FieldNo);
3165 }
3166
3167 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3168 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3169 Flags = llvm::DINode::FlagProtected;
3170 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3171 Flags = llvm::DINode::FlagPrivate;
3172 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3173 Flags = llvm::DINode::FlagPublic;
3174
3175 if (Field->isBitField())
3176 Flags |= llvm::DINode::FlagBitField;
3177
3178 llvm::MDNode *PropertyNode = nullptr;
3179 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3180 if (ObjCPropertyImplDecl *PImpD =
3181 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3182 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3183 SourceLocation Loc = PD->getLocation();
3184 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3185 unsigned PLine = getLineNumber(Loc);
3186 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3187 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3188 PropertyNode = DBuilder.createObjCProperty(
3189 PD->getName(), PUnit, PLine,
3190 hasDefaultGetterName(PD, Getter)
3191 ? ""
3192 : getSelectorName(PD->getGetterName()),
3193 hasDefaultSetterName(PD, Setter)
3194 ? ""
3195 : getSelectorName(PD->getSetterName()),
3196 PD->getPropertyAttributes(),
3197 getOrCreateType(PD->getType(), PUnit));
3198 }
3199 }
3200 }
3201 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3202 FieldSize, FieldAlign, FieldOffset, Flags,
3203 FieldTy, PropertyNode);
3204 EltTys.push_back(FieldTy);
3205 }
3206
3207 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3208 DBuilder.replaceArrays(RealDecl, Elements);
3209
3210 LexicalBlockStack.pop_back();
3211 return RealDecl;
3212}
3213
3214llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3215 llvm::DIFile *Unit) {
3216 if (Ty->isExtVectorBoolType()) {
3217 // Boolean ext_vector_type(N) are special because their real element type
3218 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3219 // For now, we pretend the boolean vector were actually a vector of bytes
3220 // (where each byte represents 8 bits of the actual vector).
3221 // FIXME Debug info should actually represent this proper as a vector mask
3222 // type.
3223 auto &Ctx = CGM.getContext();
3224 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3225 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3226
3227 // Construct the vector of 'char' type.
3228 QualType CharVecTy =
3229 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3230 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3231 }
3232
3233 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3234 int64_t Count = Ty->getNumElements();
3235
3236 llvm::Metadata *Subscript;
3237 QualType QTy(Ty, 0);
3238 auto SizeExpr = SizeExprCache.find(QTy);
3239 if (SizeExpr != SizeExprCache.end())
3240 Subscript = DBuilder.getOrCreateSubrange(
3241 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3242 nullptr /*upperBound*/, nullptr /*stride*/);
3243 else {
3244 auto *CountNode =
3245 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3246 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3247 Subscript = DBuilder.getOrCreateSubrange(
3248 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3249 nullptr /*stride*/);
3250 }
3251 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3252
3253 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3254 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3255
3256 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3257}
3258
3259llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3260 llvm::DIFile *Unit) {
3261 // FIXME: Create another debug type for matrices
3262 // For the time being, it treats it like a nested ArrayType.
3263
3264 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3265 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3266 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3267
3268 // Create ranges for both dimensions.
3270 auto *ColumnCountNode =
3271 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3272 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3273 auto *RowCountNode =
3274 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3275 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3276 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3277 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3278 nullptr /*stride*/));
3279 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3280 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3281 nullptr /*stride*/));
3282 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3283 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3284}
3285
3286llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3287 uint64_t Size;
3288 uint32_t Align;
3289
3290 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3291 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3292 Size = 0;
3294 CGM.getContext());
3295 } else if (Ty->isIncompleteArrayType()) {
3296 Size = 0;
3297 if (Ty->getElementType()->isIncompleteType())
3298 Align = 0;
3299 else
3300 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3301 } else if (Ty->isIncompleteType()) {
3302 Size = 0;
3303 Align = 0;
3304 } else {
3305 // Size and align of the whole array, not the element type.
3306 Size = CGM.getContext().getTypeSize(Ty);
3307 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3308 }
3309
3310 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3311 // interior arrays, do we care? Why aren't nested arrays represented the
3312 // obvious/recursive way?
3314 QualType EltTy(Ty, 0);
3315 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3316 // If the number of elements is known, then count is that number. Otherwise,
3317 // it's -1. This allows us to represent a subrange with an array of 0
3318 // elements, like this:
3319 //
3320 // struct foo {
3321 // int x[0];
3322 // };
3323 int64_t Count = -1; // Count == -1 is an unbounded array.
3324 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3325 Count = CAT->getZExtSize();
3326 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3327 if (Expr *Size = VAT->getSizeExpr()) {
3329 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3330 Count = Result.Val.getInt().getExtValue();
3331 }
3332 }
3333
3334 auto SizeNode = SizeExprCache.find(EltTy);
3335 if (SizeNode != SizeExprCache.end())
3336 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3337 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3338 nullptr /*upperBound*/, nullptr /*stride*/));
3339 else {
3340 auto *CountNode =
3341 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3342 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3343 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3344 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3345 nullptr /*stride*/));
3346 }
3347 EltTy = Ty->getElementType();
3348 }
3349
3350 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3351
3352 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3353 SubscriptArray);
3354}
3355
3356llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3357 llvm::DIFile *Unit) {
3358 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3359 Ty->getPointeeType(), Unit);
3360}
3361
3362llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3363 llvm::DIFile *Unit) {
3364 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3365 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3366 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3367 CGM.getCodeGenOpts().DwarfVersion < 4)
3368 Tag = llvm::dwarf::DW_TAG_reference_type;
3369
3370 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3371}
3372
3373llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3374 llvm::DIFile *U) {
3375 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3376 uint64_t Size = 0;
3377
3378 if (!Ty->isIncompleteType()) {
3379 Size = CGM.getContext().getTypeSize(Ty);
3380
3381 // Set the MS inheritance model. There is no flag for the unspecified model.
3382 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3385 Flags |= llvm::DINode::FlagSingleInheritance;
3386 break;
3388 Flags |= llvm::DINode::FlagMultipleInheritance;
3389 break;
3391 Flags |= llvm::DINode::FlagVirtualInheritance;
3392 break;
3394 break;
3395 }
3396 }
3397 }
3398
3399 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3400 if (Ty->isMemberDataPointerType())
3401 return DBuilder.createMemberPointerType(
3402 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3403 Flags);
3404
3405 const FunctionProtoType *FPT =
3407 return DBuilder.createMemberPointerType(
3408 getOrCreateInstanceMethodType(
3410 FPT, U),
3411 ClassType, Size, /*Align=*/0, Flags);
3412}
3413
3414llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3415 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3416 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3417}
3418
3419llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3420 return getOrCreateType(Ty->getElementType(), U);
3421}
3422
3423llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3424 const EnumDecl *ED = Ty->getDecl();
3425
3426 uint64_t Size = 0;
3427 uint32_t Align = 0;
3428 if (!ED->getTypeForDecl()->isIncompleteType()) {
3430 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3431 }
3432
3434
3435 bool isImportedFromModule =
3436 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3437
3438 // If this is just a forward declaration, construct an appropriately
3439 // marked node and just return it.
3440 if (isImportedFromModule || !ED->getDefinition()) {
3441 // Note that it is possible for enums to be created as part of
3442 // their own declcontext. In this case a FwdDecl will be created
3443 // twice. This doesn't cause a problem because both FwdDecls are
3444 // entered into the ReplaceMap: finalize() will replace the first
3445 // FwdDecl with the second and then replace the second with
3446 // complete type.
3447 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3448 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3449 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3450 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3451
3452 unsigned Line = getLineNumber(ED->getLocation());
3453 StringRef EDName = ED->getName();
3454 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3455 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3456 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3457
3458 ReplaceMap.emplace_back(
3459 std::piecewise_construct, std::make_tuple(Ty),
3460 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3461 return RetTy;
3462 }
3463
3464 return CreateTypeDefinition(Ty);
3465}
3466
3467llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3468 const EnumDecl *ED = Ty->getDecl();
3469 uint64_t Size = 0;
3470 uint32_t Align = 0;
3471 if (!ED->getTypeForDecl()->isIncompleteType()) {
3473 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3474 }
3475
3477
3479 ED = ED->getDefinition();
3480 for (const auto *Enum : ED->enumerators()) {
3481 Enumerators.push_back(
3482 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3483 }
3484
3485 // Return a CompositeType for the enum itself.
3486 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3487
3488 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3489 unsigned Line = getLineNumber(ED->getLocation());
3490 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3491 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3492 return DBuilder.createEnumerationType(
3493 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3494 /*RunTimeLang=*/0, Identifier, ED->isScoped());
3495}
3496
3497llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3498 unsigned MType, SourceLocation LineLoc,
3499 StringRef Name, StringRef Value) {
3500 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3501 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3502}
3503
3504llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3505 SourceLocation LineLoc,
3506 SourceLocation FileLoc) {
3507 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3508 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3509 return DBuilder.createTempMacroFile(Parent, Line, FName);
3510}
3511
3513 Qualifiers Quals;
3514 do {
3515 Qualifiers InnerQuals = T.getLocalQualifiers();
3516 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3517 // that is already there.
3518 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3519 Quals += InnerQuals;
3520 QualType LastT = T;
3521 switch (T->getTypeClass()) {
3522 default:
3523 return C.getQualifiedType(T.getTypePtr(), Quals);
3524 case Type::TemplateSpecialization: {
3525 const auto *Spec = cast<TemplateSpecializationType>(T);
3526 if (Spec->isTypeAlias())
3527 return C.getQualifiedType(T.getTypePtr(), Quals);
3528 T = Spec->desugar();
3529 break;
3530 }
3531 case Type::TypeOfExpr:
3532 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3533 break;
3534 case Type::TypeOf:
3535 T = cast<TypeOfType>(T)->getUnmodifiedType();
3536 break;
3537 case Type::Decltype:
3538 T = cast<DecltypeType>(T)->getUnderlyingType();
3539 break;
3540 case Type::UnaryTransform:
3541 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3542 break;
3543 case Type::Attributed:
3544 T = cast<AttributedType>(T)->getEquivalentType();
3545 break;
3546 case Type::BTFTagAttributed:
3547 T = cast<BTFTagAttributedType>(T)->getWrappedType();
3548 break;
3549 case Type::CountAttributed:
3550 T = cast<CountAttributedType>(T)->desugar();
3551 break;
3552 case Type::Elaborated:
3553 T = cast<ElaboratedType>(T)->getNamedType();
3554 break;
3555 case Type::Using:
3556 T = cast<UsingType>(T)->getUnderlyingType();
3557 break;
3558 case Type::Paren:
3559 T = cast<ParenType>(T)->getInnerType();
3560 break;
3561 case Type::MacroQualified:
3562 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3563 break;
3564 case Type::SubstTemplateTypeParm:
3565 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3566 break;
3567 case Type::Auto:
3568 case Type::DeducedTemplateSpecialization: {
3569 QualType DT = cast<DeducedType>(T)->getDeducedType();
3570 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3571 T = DT;
3572 break;
3573 }
3574 case Type::PackIndexing: {
3575 T = cast<PackIndexingType>(T)->getSelectedType();
3576 break;
3577 }
3578 case Type::Adjusted:
3579 case Type::Decayed:
3580 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3581 T = cast<AdjustedType>(T)->getAdjustedType();
3582 break;
3583 }
3584
3585 assert(T != LastT && "Type unwrapping failed to unwrap!");
3586 (void)LastT;
3587 } while (true);
3588}
3589
3590llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3591 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3592 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3593 if (It != TypeCache.end()) {
3594 // Verify that the debug info still exists.
3595 if (llvm::Metadata *V = It->second)
3596 return cast<llvm::DIType>(V);
3597 }
3598
3599 return nullptr;
3600}
3601
3605}
3606
3608 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
3609 D.isDynamicClass())
3610 return;
3611
3613 // In case this type has no member function definitions being emitted, ensure
3614 // it is retained
3615 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3616}
3617
3618llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3619 if (Ty.isNull())
3620 return nullptr;
3621
3622 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3623 std::string Name;
3624 llvm::raw_string_ostream OS(Name);
3625 Ty.print(OS, getPrintingPolicy());
3626 return Name;
3627 });
3628
3629 // Unwrap the type as needed for debug information.
3630 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3631
3632 if (auto *T = getTypeOrNull(Ty))
3633 return T;
3634
3635 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3636 void *TyPtr = Ty.getAsOpaquePtr();
3637
3638 // And update the type cache.
3639 TypeCache[TyPtr].reset(Res);
3640
3641 return Res;
3642}
3643
3644llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3645 // A forward declaration inside a module header does not belong to the module.
3646 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3647 return nullptr;
3648 if (DebugTypeExtRefs && D->isFromASTFile()) {
3649 // Record a reference to an imported clang module or precompiled header.
3650 auto *Reader = CGM.getContext().getExternalSource();
3651 auto Idx = D->getOwningModuleID();
3652 auto Info = Reader->getSourceDescriptor(Idx);
3653 if (Info)
3654 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3655 } else if (ClangModuleMap) {
3656 // We are building a clang module or a precompiled header.
3657 //
3658 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3659 // and it wouldn't be necessary to specify the parent scope
3660 // because the type is already unique by definition (it would look
3661 // like the output of -fno-standalone-debug). On the other hand,
3662 // the parent scope helps a consumer to quickly locate the object
3663 // file where the type's definition is located, so it might be
3664 // best to make this behavior a command line or debugger tuning
3665 // option.
3666 if (Module *M = D->getOwningModule()) {
3667 // This is a (sub-)module.
3668 auto Info = ASTSourceDescriptor(*M);
3669 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3670 } else {
3671 // This the precompiled header being built.
3672 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3673 }
3674 }
3675
3676 return nullptr;
3677}
3678
3679llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3680 // Handle qualifiers, which recursively handles what they refer to.
3681 if (Ty.hasLocalQualifiers())
3682 return CreateQualifiedType(Ty, Unit);
3683
3684 // Work out details of type.
3685 switch (Ty->getTypeClass()) {
3686#define TYPE(Class, Base)
3687#define ABSTRACT_TYPE(Class, Base)
3688#define NON_CANONICAL_TYPE(Class, Base)
3689#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3690#include "clang/AST/TypeNodes.inc"
3691 llvm_unreachable("Dependent types cannot show up in debug information");
3692
3693 case Type::ExtVector:
3694 case Type::Vector:
3695 return CreateType(cast<VectorType>(Ty), Unit);
3696 case Type::ConstantMatrix:
3697 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3698 case Type::ObjCObjectPointer:
3699 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3700 case Type::ObjCObject:
3701 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3702 case Type::ObjCTypeParam:
3703 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3704 case Type::ObjCInterface:
3705 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3706 case Type::Builtin:
3707 return CreateType(cast<BuiltinType>(Ty));
3708 case Type::Complex:
3709 return CreateType(cast<ComplexType>(Ty));
3710 case Type::Pointer:
3711 return CreateType(cast<PointerType>(Ty), Unit);
3712 case Type::BlockPointer:
3713 return CreateType(cast<BlockPointerType>(Ty), Unit);
3714 case Type::Typedef:
3715 return CreateType(cast<TypedefType>(Ty), Unit);
3716 case Type::Record:
3717 return CreateType(cast<RecordType>(Ty));
3718 case Type::Enum:
3719 return CreateEnumType(cast<EnumType>(Ty));
3720 case Type::FunctionProto:
3721 case Type::FunctionNoProto:
3722 return CreateType(cast<FunctionType>(Ty), Unit);
3723 case Type::ConstantArray:
3724 case Type::VariableArray:
3725 case Type::IncompleteArray:
3726 case Type::ArrayParameter:
3727 return CreateType(cast<ArrayType>(Ty), Unit);
3728
3729 case Type::LValueReference:
3730 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3731 case Type::RValueReference:
3732 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3733
3734 case Type::MemberPointer:
3735 return CreateType(cast<MemberPointerType>(Ty), Unit);
3736
3737 case Type::Atomic:
3738 return CreateType(cast<AtomicType>(Ty), Unit);
3739
3740 case Type::BitInt:
3741 return CreateType(cast<BitIntType>(Ty));
3742 case Type::Pipe:
3743 return CreateType(cast<PipeType>(Ty), Unit);
3744
3745 case Type::TemplateSpecialization:
3746 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3747
3748 case Type::CountAttributed:
3749 case Type::Auto:
3750 case Type::Attributed:
3751 case Type::BTFTagAttributed:
3752 case Type::Adjusted:
3753 case Type::Decayed:
3754 case Type::DeducedTemplateSpecialization:
3755 case Type::Elaborated:
3756 case Type::Using:
3757 case Type::Paren:
3758 case Type::MacroQualified:
3759 case Type::SubstTemplateTypeParm:
3760 case Type::TypeOfExpr:
3761 case Type::TypeOf:
3762 case Type::Decltype:
3763 case Type::PackIndexing:
3764 case Type::UnaryTransform:
3765 break;
3766 }
3767
3768 llvm_unreachable("type should have been unwrapped!");
3769}
3770
3771llvm::DICompositeType *
3772CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3773 QualType QTy(Ty, 0);
3774
3775 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3776
3777 // We may have cached a forward decl when we could have created
3778 // a non-forward decl. Go ahead and create a non-forward decl
3779 // now.
3780 if (T && !T->isForwardDecl())
3781 return T;
3782
3783 // Otherwise create the type.
3784 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3785
3786 // Propagate members from the declaration to the definition
3787 // CreateType(const RecordType*) will overwrite this with the members in the
3788 // correct order if the full type is needed.
3789 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3790
3791 // And update the type cache.
3792 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3793 return Res;
3794}
3795
3796// TODO: Currently used for context chains when limiting debug info.
3797llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3798 RecordDecl *RD = Ty->getDecl();
3799
3800 // Get overall information about the record type for the debug info.
3801 StringRef RDName = getClassName(RD);
3802 const SourceLocation Loc = RD->getLocation();
3803 llvm::DIFile *DefUnit = nullptr;
3804 unsigned Line = 0;
3805 if (Loc.isValid()) {
3806 DefUnit = getOrCreateFile(Loc);
3807 Line = getLineNumber(Loc);
3808 }
3809
3810 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3811
3812 // If we ended up creating the type during the context chain construction,
3813 // just return that.
3814 auto *T = cast_or_null<llvm::DICompositeType>(
3815 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3816 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3817 return T;
3818
3819 // If this is just a forward or incomplete declaration, construct an
3820 // appropriately marked node and just return it.
3821 const RecordDecl *D = RD->getDefinition();
3822 if (!D || !D->isCompleteDefinition())
3823 return getOrCreateRecordFwdDecl(Ty, RDContext);
3824
3825 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3826 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3827 // struct or struct member, where it only increases alignment unless 'packed'
3828 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3829 // to be used.
3830 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3831
3833
3834 // Explicitly record the calling convention and export symbols for C++
3835 // records.
3836 auto Flags = llvm::DINode::FlagZero;
3837 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3839 Flags |= llvm::DINode::FlagTypePassByReference;
3840 else
3841 Flags |= llvm::DINode::FlagTypePassByValue;
3842
3843 // Record if a C++ record is non-trivial type.
3844 if (!CXXRD->isTrivial())
3845 Flags |= llvm::DINode::FlagNonTrivial;
3846
3847 // Record exports it symbols to the containing structure.
3848 if (CXXRD->isAnonymousStructOrUnion())
3849 Flags |= llvm::DINode::FlagExportSymbols;
3850
3851 Flags |= getAccessFlag(CXXRD->getAccess(),
3852 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3853 }
3854
3855 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3856 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3857 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3858 Flags, Identifier, Annotations);
3859
3860 // Elements of composite types usually have back to the type, creating
3861 // uniquing cycles. Distinct nodes are more efficient.
3862 switch (RealDecl->getTag()) {
3863 default:
3864 llvm_unreachable("invalid composite type tag");
3865
3866 case llvm::dwarf::DW_TAG_array_type:
3867 case llvm::dwarf::DW_TAG_enumeration_type:
3868 // Array elements and most enumeration elements don't have back references,
3869 // so they don't tend to be involved in uniquing cycles and there is some
3870 // chance of merging them when linking together two modules. Only make
3871 // them distinct if they are ODR-uniqued.
3872 if (Identifier.empty())
3873 break;
3874 [[fallthrough]];
3875
3876 case llvm::dwarf::DW_TAG_structure_type:
3877 case llvm::dwarf::DW_TAG_union_type:
3878 case llvm::dwarf::DW_TAG_class_type:
3879 // Immediately resolve to a distinct node.
3880 RealDecl =
3881 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3882 break;
3883 }
3884
3885 RegionMap[Ty->getDecl()].reset(RealDecl);
3886 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3887
3888 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3889 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3890 CollectCXXTemplateParams(TSpecial, DefUnit));
3891 return RealDecl;
3892}
3893
3894void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3895 llvm::DICompositeType *RealDecl) {
3896 // A class's primary base or the class itself contains the vtable.
3897 llvm::DIType *ContainingType = nullptr;
3898 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3899 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3900 // Seek non-virtual primary base root.
3901 while (true) {
3902 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3903 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3904 if (PBT && !BRL.isPrimaryBaseVirtual())
3905 PBase = PBT;
3906 else
3907 break;
3908 }
3909 ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3910 getOrCreateFile(RD->getLocation()));
3911 } else if (RD->isDynamicClass())
3912 ContainingType = RealDecl;
3913
3914 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3915}
3916
3917llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3918 StringRef Name, uint64_t *Offset) {
3919 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3920 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3921 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3922 llvm::DIType *Ty =
3923 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3924 *Offset, llvm::DINode::FlagZero, FieldTy);
3925 *Offset += FieldSize;
3926 return Ty;
3927}
3928
3929void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3930 StringRef &Name,
3931 StringRef &LinkageName,
3932 llvm::DIScope *&FDContext,
3933 llvm::DINodeArray &TParamsArray,
3934 llvm::DINode::DIFlags &Flags) {
3935 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3936 Name = getFunctionName(FD);
3937 // Use mangled name as linkage name for C/C++ functions.
3938 if (FD->getType()->getAs<FunctionProtoType>())
3939 LinkageName = CGM.getMangledName(GD);
3940 if (FD->hasPrototype())
3941 Flags |= llvm::DINode::FlagPrototyped;
3942 // No need to replicate the linkage name if it isn't different from the
3943 // subprogram name, no need to have it at all unless coverage is enabled or
3944 // debug is set to more than just line tables or extra debug info is needed.
3945 if (LinkageName == Name ||
3946 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
3947 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
3948 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3949 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
3950 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
3951 LinkageName = StringRef();
3952
3953 // Emit the function scope in line tables only mode (if CodeView) to
3954 // differentiate between function names.
3955 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3956 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
3957 CGM.getCodeGenOpts().EmitCodeView)) {
3958 if (const NamespaceDecl *NSDecl =
3959 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3960 FDContext = getOrCreateNamespace(NSDecl);
3961 else if (const RecordDecl *RDecl =
3962 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3963 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3964 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3965 }
3966 }
3967 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3968 // Check if it is a noreturn-marked function
3969 if (FD->isNoReturn())
3970 Flags |= llvm::DINode::FlagNoReturn;
3971 // Collect template parameters.
3972 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3973 }
3974}
3975
3976void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3977 unsigned &LineNo, QualType &T,
3978 StringRef &Name, StringRef &LinkageName,
3979 llvm::MDTuple *&TemplateParameters,
3980 llvm::DIScope *&VDContext) {
3981 Unit = getOrCreateFile(VD->getLocation());
3982 LineNo = getLineNumber(VD->getLocation());
3983
3984 setLocation(VD->getLocation());
3985
3986 T = VD->getType();
3987 if (T->isIncompleteArrayType()) {
3988 // CodeGen turns int[] into int[1] so we'll do the same here.
3989 llvm::APInt ConstVal(32, 1);
3991
3992 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3994 }
3995
3996 Name = VD->getName();
3997 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3998 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3999 LinkageName = CGM.getMangledName(VD);
4000 if (LinkageName == Name)
4001 LinkageName = StringRef();
4002
4003 if (isa<VarTemplateSpecializationDecl>(VD)) {
4004 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4005 TemplateParameters = parameterNodes.get();
4006 } else {
4007 TemplateParameters = nullptr;
4008 }
4009
4010 // Since we emit declarations (DW_AT_members) for static members, place the
4011 // definition of those static members in the namespace they were declared in
4012 // in the source code (the lexical decl context).
4013 // FIXME: Generalize this for even non-member global variables where the
4014 // declaration and definition may have different lexical decl contexts, once
4015 // we have support for emitting declarations of (non-member) global variables.
4016 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4017 : VD->getDeclContext();
4018 // When a record type contains an in-line initialization of a static data
4019 // member, and the record type is marked as __declspec(dllexport), an implicit
4020 // definition of the member will be created in the record context. DWARF
4021 // doesn't seem to have a nice way to describe this in a form that consumers
4022 // are likely to understand, so fake the "normal" situation of a definition
4023 // outside the class by putting it in the global scope.
4024 if (DC->isRecord())
4026
4027 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4028 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4029}
4030
4031llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4032 bool Stub) {
4033 llvm::DINodeArray TParamsArray;
4034 StringRef Name, LinkageName;
4035 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4036 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4038 llvm::DIFile *Unit = getOrCreateFile(Loc);
4039 llvm::DIScope *DContext = Unit;
4040 unsigned Line = getLineNumber(Loc);
4041 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4042 Flags);
4043 auto *FD = cast<FunctionDecl>(GD.getDecl());
4044
4045 // Build function type.
4047 for (const ParmVarDecl *Parm : FD->parameters())
4048 ArgTypes.push_back(Parm->getType());
4049
4050 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4051 QualType FnType = CGM.getContext().getFunctionType(
4052 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4053 if (!FD->isExternallyVisible())
4054 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4055 if (CGM.getLangOpts().Optimize)
4056 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4057
4058 if (Stub) {
4059 Flags |= getCallSiteRelatedAttrs();
4060 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4061 return DBuilder.createFunction(
4062 DContext, Name, LinkageName, Unit, Line,
4063 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4064 TParamsArray.get(), getFunctionDeclaration(FD));
4065 }
4066
4067 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4068 DContext, Name, LinkageName, Unit, Line,
4069 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4070 TParamsArray.get(), getFunctionDeclaration(FD));
4071 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4072 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4073 std::make_tuple(CanonDecl),
4074 std::make_tuple(SP));
4075 return SP;
4076}
4077
4078llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4079 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4080}
4081
4082llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4083 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4084}
4085
4086llvm::DIGlobalVariable *
4087CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4088 QualType T;
4089 StringRef Name, LinkageName;
4091 llvm::DIFile *Unit = getOrCreateFile(Loc);
4092 llvm::DIScope *DContext = Unit;
4093 unsigned Line = getLineNumber(Loc);
4094 llvm::MDTuple *TemplateParameters = nullptr;
4095
4096 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4097 DContext);
4098 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4099 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4100 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4101 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4102 FwdDeclReplaceMap.emplace_back(
4103 std::piecewise_construct,
4104 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4105 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4106 return GV;
4107}
4108
4109llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4110 // We only need a declaration (not a definition) of the type - so use whatever
4111 // we would otherwise do to get a type for a pointee. (forward declarations in
4112 // limited debug info, full definitions (if the type definition is available)
4113 // in unlimited debug info)
4114 if (const auto *TD = dyn_cast<TypeDecl>(D))
4115 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
4116 getOrCreateFile(TD->getLocation()));
4117 auto I = DeclCache.find(D->getCanonicalDecl());
4118
4119 if (I != DeclCache.end()) {
4120 auto N = I->second;
4121 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4122 return GVE->getVariable();
4123 return cast<llvm::DINode>(N);
4124 }
4125
4126 // Search imported declaration cache if it is already defined
4127 // as imported declaration.
4128 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4129
4130 if (IE != ImportedDeclCache.end()) {
4131 auto N = IE->second;
4132 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4133 return cast<llvm::DINode>(GVE);
4134 return dyn_cast_or_null<llvm::DINode>(N);
4135 }
4136
4137 // No definition for now. Emit a forward definition that might be
4138 // merged with a potential upcoming definition.
4139 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4140 return getFunctionForwardDeclaration(FD);
4141 else if (const auto *VD = dyn_cast<VarDecl>(D))
4142 return getGlobalVariableForwardDeclaration(VD);
4143
4144 return nullptr;
4145}
4146
4147llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4148 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4149 return nullptr;
4150
4151 const auto *FD = dyn_cast<FunctionDecl>(D);
4152 if (!FD)
4153 return nullptr;
4154
4155 // Setup context.
4156 auto *S = getDeclContextDescriptor(D);
4157
4158 auto MI = SPCache.find(FD->getCanonicalDecl());
4159 if (MI == SPCache.end()) {
4160 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4161 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4162 cast<llvm::DICompositeType>(S));
4163 }
4164 }
4165 if (MI != SPCache.end()) {
4166 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4167 if (SP && !SP->isDefinition())
4168 return SP;
4169 }
4170
4171 for (auto *NextFD : FD->redecls()) {
4172 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4173 if (MI != SPCache.end()) {
4174 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4175 if (SP && !SP->isDefinition())
4176 return SP;
4177 }
4178 }
4179 return nullptr;
4180}
4181
4182llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4183 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4184 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4185 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4186 return nullptr;
4187
4188 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4189 if (!OMD)
4190 return nullptr;
4191
4192 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4193 return nullptr;
4194
4195 if (OMD->isDirectMethod())
4196 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4197
4198 // Starting with DWARF V5 method declarations are emitted as children of
4199 // the interface type.
4200 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4201 if (!ID)
4202 ID = OMD->getClassInterface();
4203 if (!ID)
4204 return nullptr;
4205 QualType QTy(ID->getTypeForDecl(), 0);
4206 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4207 if (It == TypeCache.end())
4208 return nullptr;
4209 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4210 llvm::DISubprogram *FD = DBuilder.createFunction(
4211 InterfaceType, getObjCMethodName(OMD), StringRef(),
4212 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4213 DBuilder.finalizeSubprogram(FD);
4214 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4215 return FD;
4216}
4217
4218// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4219// implicit parameter "this".
4220llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4221 QualType FnType,
4222 llvm::DIFile *F) {
4223 // In CodeView, we emit the function types in line tables only because the
4224 // only way to distinguish between functions is by display name and type.
4225 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4226 !CGM.getCodeGenOpts().EmitCodeView))
4227 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4228 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4229 return DBuilder.createSubroutineType(
4230 DBuilder.getOrCreateTypeArray(std::nullopt));
4231
4232 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4233 return getOrCreateMethodType(Method, F);
4234
4235 const auto *FTy = FnType->getAs<FunctionType>();
4236 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4237
4238 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4239 // Add "self" and "_cmd"
4241
4242 // First element is always return type. For 'void' functions it is NULL.
4243 QualType ResultTy = OMethod->getReturnType();
4244
4245 // Replace the instancetype keyword with the actual type.
4246 if (ResultTy == CGM.getContext().getObjCInstanceType())
4247 ResultTy = CGM.getContext().getPointerType(
4248 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4249
4250 Elts.push_back(getOrCreateType(ResultTy, F));
4251 // "self" pointer is always first argument.
4252 QualType SelfDeclTy;
4253 if (auto *SelfDecl = OMethod->getSelfDecl())
4254 SelfDeclTy = SelfDecl->getType();
4255 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4256 if (FPT->getNumParams() > 1)
4257 SelfDeclTy = FPT->getParamType(0);
4258 if (!SelfDeclTy.isNull())
4259 Elts.push_back(
4260 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4261 // "_cmd" pointer is always second argument.
4262 Elts.push_back(DBuilder.createArtificialType(
4263 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4264 // Get rest of the arguments.
4265 for (const auto *PI : OMethod->parameters())
4266 Elts.push_back(getOrCreateType(PI->getType(), F));
4267 // Variadic methods need a special marker at the end of the type list.
4268 if (OMethod->isVariadic())
4269 Elts.push_back(DBuilder.createUnspecifiedParameter());
4270
4271 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4272 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4273 getDwarfCC(CC));
4274 }
4275
4276 // Handle variadic function types; they need an additional
4277 // unspecified parameter.
4278 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4279 if (FD->isVariadic()) {
4281 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4282 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4283 for (QualType ParamType : FPT->param_types())
4284 EltTys.push_back(getOrCreateType(ParamType, F));
4285 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4286 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4287 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4288 getDwarfCC(CC));
4289 }
4290
4291 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4292}
4293
4298 if (FD)
4299 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4300 CC = SrcFnTy->getCallConv();
4302 for (const VarDecl *VD : Args)
4303 ArgTypes.push_back(VD->getType());
4304 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4306}
4307
4309 SourceLocation ScopeLoc, QualType FnType,
4310 llvm::Function *Fn, bool CurFuncIsThunk) {
4311 StringRef Name;
4312 StringRef LinkageName;
4313
4314 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4315
4316 const Decl *D = GD.getDecl();
4317 bool HasDecl = (D != nullptr);
4318
4319 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4320 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4321 llvm::DIFile *Unit = getOrCreateFile(Loc);
4322 llvm::DIScope *FDContext = Unit;
4323 llvm::DINodeArray TParamsArray;
4324 if (!HasDecl) {
4325 // Use llvm function name.
4326 LinkageName = Fn->getName();
4327 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4328 // If there is a subprogram for this function available then use it.
4329 auto FI = SPCache.find(FD->getCanonicalDecl());
4330 if (FI != SPCache.end()) {
4331 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4332 if (SP && SP->isDefinition()) {
4333 LexicalBlockStack.emplace_back(SP);
4334 RegionMap[D].reset(SP);
4335 return;
4336 }
4337 }
4338 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4339 TParamsArray, Flags);
4340 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4341 Name = getObjCMethodName(OMD);
4342 Flags |= llvm::DINode::FlagPrototyped;
4343 } else if (isa<VarDecl>(D) &&
4345 // This is a global initializer or atexit destructor for a global variable.
4346 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4347 Fn);
4348 } else {
4349 Name = Fn->getName();
4350
4351 if (isa<BlockDecl>(D))
4352 LinkageName = Name;
4353
4354 Flags |= llvm::DINode::FlagPrototyped;
4355 }
4356 if (Name.starts_with("\01"))
4357 Name = Name.substr(1);
4358
4359 assert((!D || !isa<VarDecl>(D) ||
4361 "Unexpected DynamicInitKind !");
4362
4363 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4364 isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4365 Flags |= llvm::DINode::FlagArtificial;
4366 // Artificial functions should not silently reuse CurLoc.
4367 CurLoc = SourceLocation();
4368 }
4369
4370 if (CurFuncIsThunk)
4371 Flags |= llvm::DINode::FlagThunk;
4372
4373 if (Fn->hasLocalLinkage())
4374 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4375 if (CGM.getLangOpts().Optimize)
4376 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4377
4378 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4379 llvm::DISubprogram::DISPFlags SPFlagsForDef =
4380 SPFlags | llvm::DISubprogram::SPFlagDefinition;
4381
4382 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4383 unsigned ScopeLine = getLineNumber(ScopeLoc);
4384 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4385 llvm::DISubprogram *Decl = nullptr;
4386 llvm::DINodeArray Annotations = nullptr;
4387 if (D) {
4388 Decl = isa<ObjCMethodDecl>(D)
4389 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4390 : getFunctionDeclaration(D);
4391 Annotations = CollectBTFDeclTagAnnotations(D);
4392 }
4393
4394 // FIXME: The function declaration we're constructing here is mostly reusing
4395 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4396 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4397 // all subprograms instead of the actual context since subprogram definitions
4398 // are emitted as CU level entities by the backend.
4399 llvm::DISubprogram *SP = DBuilder.createFunction(
4400 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4401 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4402 Annotations);
4403 Fn->setSubprogram(SP);
4404 // We might get here with a VarDecl in the case we're generating
4405 // code for the initialization of globals. Do not record these decls
4406 // as they will overwrite the actual VarDecl Decl in the cache.
4407 if (HasDecl && isa<FunctionDecl>(D))
4408 DeclCache[D->getCanonicalDecl()].reset(SP);
4409
4410 // Push the function onto the lexical block stack.
4411 LexicalBlockStack.emplace_back(SP);
4412
4413 if (HasDecl)
4414 RegionMap[D].reset(SP);
4415}
4416
4418 QualType FnType, llvm::Function *Fn) {
4419 StringRef Name;
4420 StringRef LinkageName;
4421
4422 const Decl *D = GD.getDecl();
4423 if (!D)
4424 return;
4425
4426 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4427 return GetName(D, true);
4428 });
4429
4430 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4431 llvm::DIFile *Unit = getOrCreateFile(Loc);
4432 bool IsDeclForCallSite = Fn ? true : false;
4433 llvm::DIScope *FDContext =
4434 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4435 llvm::DINodeArray TParamsArray;
4436 if (isa<FunctionDecl>(D)) {
4437 // If there is a DISubprogram for this function available then use it.
4438 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4439 TParamsArray, Flags);
4440 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4441 Name = getObjCMethodName(OMD);
4442 Flags |= llvm::DINode::FlagPrototyped;
4443 } else {
4444 llvm_unreachable("not a function or ObjC method");
4445 }
4446 if (!Name.empty() && Name[0] == '\01')
4447 Name = Name.substr(1);
4448
4449 if (D->isImplicit()) {
4450 Flags |= llvm::DINode::FlagArtificial;
4451 // Artificial functions without a location should not silently reuse CurLoc.
4452 if (Loc.isInvalid())
4453 CurLoc = SourceLocation();
4454 }
4455 unsigned LineNo = getLineNumber(Loc);
4456 unsigned ScopeLine = 0;
4457 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4458 if (CGM.getLangOpts().Optimize)
4459 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4460
4461 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4462 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4463 llvm::DISubprogram *SP = DBuilder.createFunction(
4464 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4465 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
4466
4467 // Preserve btf_decl_tag attributes for parameters of extern functions
4468 // for BPF target. The parameters created in this loop are attached as
4469 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4470 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4471 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4472 llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4473 unsigned ArgNo = 1;
4474 for (ParmVarDecl *PD : FD->parameters()) {
4475 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4476 DBuilder.createParameterVariable(
4477 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4478 llvm::DINode::FlagZero, ParamAnnotations);
4479 ++ArgNo;
4480 }
4481 }
4482 }
4483
4484 if (IsDeclForCallSite)
4485 Fn->setSubprogram(SP);
4486
4487 DBuilder.finalizeSubprogram(SP);
4488}
4489
4490void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4491 QualType CalleeType,
4492 const FunctionDecl *CalleeDecl) {
4493 if (!CallOrInvoke)
4494 return;
4495 auto *Func = CallOrInvoke->getCalledFunction();
4496 if (!Func)
4497 return;
4498 if (Func->getSubprogram())
4499 return;
4500
4501 // Do not emit a declaration subprogram for a function with nodebug
4502 // attribute, or if call site info isn't required.
4503 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4504 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4505 return;
4506
4507 // If there is no DISubprogram attached to the function being called,
4508 // create the one describing the function in order to have complete
4509 // call site debug info.
4510 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4511 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4512}
4513
4515 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4516 // If there is a subprogram for this function available then use it.
4517 auto FI = SPCache.find(FD->getCanonicalDecl());
4518 llvm::DISubprogram *SP = nullptr;
4519 if (FI != SPCache.end())
4520 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4521 if (!SP || !SP->isDefinition())
4522 SP = getFunctionStub(GD);
4523 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4524 LexicalBlockStack.emplace_back(SP);
4525 setInlinedAt(Builder.getCurrentDebugLocation());
4526 EmitLocation(Builder, FD->getLocation());
4527}
4528
4530 assert(CurInlinedAt && "unbalanced inline scope stack");
4531 EmitFunctionEnd(Builder, nullptr);
4532 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4533}
4534
4536 // Update our current location
4538
4539 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4540 return;
4541
4542 llvm::MDNode *Scope = LexicalBlockStack.back();
4543 Builder.SetCurrentDebugLocation(
4544 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4545 getColumnNumber(CurLoc), Scope, CurInlinedAt));
4546}
4547
4548void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4549 llvm::MDNode *Back = nullptr;
4550 if (!LexicalBlockStack.empty())
4551 Back = LexicalBlockStack.back().get();
4552 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4553 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4554 getColumnNumber(CurLoc)));
4555}
4556
4557void CGDebugInfo::AppendAddressSpaceXDeref(
4558 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4559 std::optional<unsigned> DWARFAddressSpace =
4560 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4561 if (!DWARFAddressSpace)
4562 return;
4563
4564 Expr.push_back(llvm::dwarf::DW_OP_constu);
4565 Expr.push_back(*DWARFAddressSpace);
4566 Expr.push_back(llvm::dwarf::DW_OP_swap);
4567 Expr.push_back(llvm::dwarf::DW_OP_xderef);
4568}
4569
4572 // Set our current location.
4574
4575 // Emit a line table change for the current location inside the new scope.
4576 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4577 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4578 LexicalBlockStack.back(), CurInlinedAt));
4579
4580 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4581 return;
4582
4583 // Create a new lexical block and push it on the stack.
4584 CreateLexicalBlock(Loc);
4585}
4586
4589 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4590
4591 // Provide an entry in the line table for the end of the block.
4592 EmitLocation(Builder, Loc);
4593
4594 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4595 return;
4596
4597 LexicalBlockStack.pop_back();
4598}
4599
4600void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4601 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4602 unsigned RCount = FnBeginRegionCount.back();
4603 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4604
4605 // Pop all regions for this function.
4606 while (LexicalBlockStack.size() != RCount) {
4607 // Provide an entry in the line table for the end of the block.
4608 EmitLocation(Builder, CurLoc);
4609 LexicalBlockStack.pop_back();
4610 }
4611 FnBeginRegionCount.pop_back();
4612
4613 if (Fn && Fn->getSubprogram())
4614 DBuilder.finalizeSubprogram(Fn->getSubprogram());
4615}
4616
4617CGDebugInfo::BlockByRefType
4618CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4619 uint64_t *XOffset) {
4621 QualType FType;
4622 uint64_t FieldSize, FieldOffset;
4623 uint32_t FieldAlign;
4624
4625 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4626 QualType Type = VD->getType();
4627
4628 FieldOffset = 0;
4629 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4630 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4631 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4632 FType = CGM.getContext().IntTy;
4633 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4634 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4635
4636 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4637 if (HasCopyAndDispose) {
4638 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4639 EltTys.push_back(
4640 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4641 EltTys.push_back(
4642 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4643 }
4644 bool HasByrefExtendedLayout;
4645 Qualifiers::ObjCLifetime Lifetime;
4646 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4647 HasByrefExtendedLayout) &&
4648 HasByrefExtendedLayout) {
4649 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4650 EltTys.push_back(
4651 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4652 }
4653
4654 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4655 if (Align > CGM.getContext().toCharUnitsFromBits(
4657 CharUnits FieldOffsetInBytes =
4658 CGM.getContext().toCharUnitsFromBits(FieldOffset);
4659 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4660 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4661
4662 if (NumPaddingBytes.isPositive()) {
4663 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4664 FType = CGM.getContext().getConstantArrayType(
4665 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
4666 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4667 }
4668 }
4669
4670 FType = Type;
4671 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4672 FieldSize = CGM.getContext().getTypeSize(FType);
4673 FieldAlign = CGM.getContext().toBits(Align);
4674
4675 *XOffset = FieldOffset;
4676 llvm::DIType *FieldTy = DBuilder.createMemberType(
4677 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4678 llvm::DINode::FlagZero, WrappedTy);
4679 EltTys.push_back(FieldTy);
4680 FieldOffset += FieldSize;
4681
4682 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4683 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4684 llvm::DINode::FlagZero, nullptr, Elements),
4685 WrappedTy};
4686}
4687
4688llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4689 llvm::Value *Storage,
4690 std::optional<unsigned> ArgNo,
4691 CGBuilderTy &Builder,
4692 const bool UsePointerValue) {
4693 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4694 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4695 if (VD->hasAttr<NoDebugAttr>())
4696 return nullptr;
4697
4698 bool Unwritten =
4699 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4700 cast<Decl>(VD->getDeclContext())->isImplicit());
4701 llvm::DIFile *Unit = nullptr;
4702 if (!Unwritten)
4703 Unit = getOrCreateFile(VD->getLocation());
4704 llvm::DIType *Ty;
4705 uint64_t XOffset = 0;
4706 if (VD->hasAttr<BlocksAttr>())
4707 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4708 else
4709 Ty = getOrCreateType(VD->getType(), Unit);
4710
4711 // If there is no debug info for this type then do not emit debug info
4712 // for this variable.
4713 if (!Ty)
4714 return nullptr;
4715
4716 // Get location information.
4717 unsigned Line = 0;
4718 unsigned Column = 0;
4719 if (!Unwritten) {
4720 Line = getLineNumber(VD->getLocation());
4721 Column = getColumnNumber(VD->getLocation());
4722 }
4724 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4725 if (VD->isImplicit())
4726 Flags |= llvm::DINode::FlagArtificial;
4727
4728 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4729
4730 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
4731 AppendAddressSpaceXDeref(AddressSpace, Expr);
4732
4733 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4734 // object pointer flag.
4735 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4736 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
4737 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
4738 Flags |= llvm::DINode::FlagObjectPointer;
4739 }
4740
4741 // Note: Older versions of clang used to emit byval references with an extra
4742 // DW_OP_deref, because they referenced the IR arg directly instead of
4743 // referencing an alloca. Newer versions of LLVM don't treat allocas
4744 // differently from other function arguments when used in a dbg.declare.
4745 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4746 StringRef Name = VD->getName();
4747 if (!Name.empty()) {
4748 // __block vars are stored on the heap if they are captured by a block that
4749 // can escape the local scope.
4750 if (VD->isEscapingByref()) {
4751 // Here, we need an offset *into* the alloca.
4753 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4754 // offset of __forwarding field
4755 offset = CGM.getContext().toCharUnitsFromBits(
4757 Expr.push_back(offset.getQuantity());
4758 Expr.push_back(llvm::dwarf::DW_OP_deref);
4759 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4760 // offset of x field
4761 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4762 Expr.push_back(offset.getQuantity());
4763 }
4764 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4765 // If VD is an anonymous union then Storage represents value for
4766 // all union fields.
4767 const RecordDecl *RD = RT->getDecl();
4768 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4769 // GDB has trouble finding local variables in anonymous unions, so we emit
4770 // artificial local variables for each of the members.
4771 //
4772 // FIXME: Remove this code as soon as GDB supports this.
4773 // The debug info verifier in LLVM operates based on the assumption that a
4774 // variable has the same size as its storage and we had to disable the
4775 // check for artificial variables.
4776 for (const auto *Field : RD->fields()) {
4777 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4778 StringRef FieldName = Field->getName();
4779
4780 // Ignore unnamed fields. Do not ignore unnamed records.
4781 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4782 continue;
4783
4784 // Use VarDecl's Tag, Scope and Line number.
4785 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4786 auto *D = DBuilder.createAutoVariable(
4787 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4788 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4789
4790 // Insert an llvm.dbg.declare into the current block.
4791 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4792 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4793 Column, Scope,
4794 CurInlinedAt),
4795 Builder.GetInsertBlock());
4796 }
4797 }
4798 }
4799
4800 // Clang stores the sret pointer provided by the caller in a static alloca.
4801 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4802 // the address of the variable.
4803 if (UsePointerValue) {
4804 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4805 "Debug info already contains DW_OP_deref.");
4806 Expr.push_back(llvm::dwarf::DW_OP_deref);
4807 }
4808
4809 // Create the descriptor for the variable.
4810 llvm::DILocalVariable *D = nullptr;
4811 if (ArgNo) {
4812 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4813 D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4814 CGM.getLangOpts().Optimize, Flags,
4815 Annotations);
4816 } else {
4817 // For normal local variable, we will try to find out whether 'VD' is the
4818 // copy parameter of coroutine.
4819 // If yes, we are going to use DIVariable of the origin parameter instead
4820 // of creating the new one.
4821 // If no, it might be a normal alloc, we just create a new one for it.
4822
4823 // Check whether the VD is move parameters.
4824 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4825 // The scope of parameter and move-parameter should be distinct
4826 // DISubprogram.
4827 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4828 return nullptr;
4829
4830 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4831 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4832 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4833 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4834 Decl *Decl = DeclGroup.getSingleDecl();
4835 if (VD == dyn_cast_or_null<VarDecl>(Decl))
4836 return true;
4837 }
4838 return false;
4839 });
4840
4841 if (Iter != CoroutineParameterMappings.end()) {
4842 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4843 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4844 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4845 });
4846 if (Iter2 != ParamDbgMappings.end())
4847 return const_cast<llvm::DILocalVariable *>(Iter2->second);
4848 }
4849 return nullptr;
4850 };
4851
4852 // If we couldn't find a move param DIVariable, create a new one.
4853 D = RemapCoroArgToLocalVar();
4854 // Or we will create a new DIVariable for this Decl if D dose not exists.
4855 if (!D)
4856 D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4857 CGM.getLangOpts().Optimize, Flags, Align);
4858 }
4859 // Insert an llvm.dbg.declare into the current block.
4860 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4861 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4862 Column, Scope, CurInlinedAt),
4863 Builder.GetInsertBlock());
4864
4865 return D;
4866}
4867
4868llvm::DIType *CGDebugInfo::CreateBindingDeclType(const BindingDecl *BD) {
4869 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4870
4871 // If the declaration is bound to a bitfield struct field, its type may have a
4872 // size that is different from its deduced declaration type's.
4873 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
4874 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
4875 if (FD->isBitField()) {
4876 ASTContext &Context = CGM.getContext();
4877 const CGRecordLayout &RL =
4878 CGM.getTypes().getCGRecordLayout(FD->getParent());
4879 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
4880
4881 // Find an integer type with the same bitwidth as the bitfield size. If
4882 // no suitable type is present in the target, give up on producing debug
4883 // information as it would be wrong. It is certainly possible to produce
4884 // correct debug info, but the logic isn't currently implemented.
4885 uint64_t BitfieldSizeInBits = Info.Size;
4886 QualType IntTy =
4887 Context.getIntTypeForBitwidth(BitfieldSizeInBits, Info.IsSigned);
4888 if (IntTy.isNull())
4889 return nullptr;
4890 Qualifiers Quals = BD->getType().getQualifiers();
4891 QualType FinalTy = Context.getQualifiedType(IntTy, Quals);
4892 llvm::DIType *Ty = getOrCreateType(FinalTy, Unit);
4893 assert(Ty);
4894 return Ty;
4895 }
4896 }
4897 }
4898
4899 return getOrCreateType(BD->getType(), Unit);
4900}
4901
4902llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4903 llvm::Value *Storage,
4904 std::optional<unsigned> ArgNo,
4905 CGBuilderTy &Builder,
4906 const bool UsePointerValue) {
4907 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4908 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4909 if (BD->hasAttr<NoDebugAttr>())
4910 return nullptr;
4911
4912 // Skip the tuple like case, we don't handle that here
4913 if (isa<DeclRefExpr>(BD->getBinding()))
4914 return nullptr;
4915
4916 llvm::DIType *Ty = CreateBindingDeclType(BD);
4917
4918 // If there is no debug info for this type then do not emit debug info
4919 // for this variable.
4920 if (!Ty)
4921 return nullptr;
4922
4923 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4924 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
4925
4927 AppendAddressSpaceXDeref(AddressSpace, Expr);
4928
4929 // Clang stores the sret pointer provided by the caller in a static alloca.
4930 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4931 // the address of the variable.
4932 if (UsePointerValue) {
4933 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4934 "Debug info already contains DW_OP_deref.");
4935 Expr.push_back(llvm::dwarf::DW_OP_deref);
4936 }
4937
4938 unsigned Line = getLineNumber(BD->getLocation());
4939 unsigned Column = getColumnNumber(BD->getLocation());
4940 StringRef Name = BD->getName();
4941 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4942 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4943 // Create the descriptor for the variable.
4944 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
4945 Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
4946 llvm::DINode::FlagZero, Align);
4947
4948 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
4949 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
4950 const unsigned fieldIndex = FD->getFieldIndex();
4951 const clang::CXXRecordDecl *parent =
4952 (const CXXRecordDecl *)FD->getParent();
4953 const ASTRecordLayout &layout =
4954 CGM.getContext().getASTRecordLayout(parent);
4955 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
4956
4957 if (fieldOffset != 0) {
4958 // Currently if the field offset is not a multiple of byte, the produced
4959 // location would not be accurate. Therefore give up.
4960 if (fieldOffset % CGM.getContext().getCharWidth() != 0)
4961 return nullptr;
4962
4963 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4964 Expr.push_back(
4965 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
4966 }
4967 }
4968 } else if (const ArraySubscriptExpr *ASE =
4969 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
4970 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
4971 const uint64_t value = IL->getValue().getZExtValue();
4972 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
4973
4974 if (value != 0) {
4975 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4976 Expr.push_back(CGM.getContext()
4977 .toCharUnitsFromBits(value * typeSize)
4978 .getQuantity());
4979 }
4980 }
4981 }
4982
4983 // Insert an llvm.dbg.declare into the current block.
4984 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4985 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4986 Column, Scope, CurInlinedAt),
4987 Builder.GetInsertBlock());
4988
4989 return D;
4990}
4991
4992llvm::DILocalVariable *
4993CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4994 CGBuilderTy &Builder,
4995 const bool UsePointerValue) {
4996 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4997
4998 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
4999 for (auto *B : DD->bindings()) {
5000 EmitDeclare(B, Storage, std::nullopt, Builder,
5001 VD->getType()->isReferenceType());
5002 }
5003 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5004 // correspond to a user variable.
5005 return nullptr;
5006 }
5007
5008 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5009}
5010
5012 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5013 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5014
5015 if (D->hasAttr<NoDebugAttr>())
5016 return;
5017
5018 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5019 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5020
5021 // Get location information.
5022 unsigned Line = getLineNumber(D->getLocation());
5023 unsigned Column = getColumnNumber(D->getLocation());
5024
5025 StringRef Name = D->getName();
5026
5027 // Create the descriptor for the label.
5028 auto *L =
5029 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
5030
5031 // Insert an llvm.dbg.label into the current block.
5032 DBuilder.insertLabel(L,
5033 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5034 Scope, CurInlinedAt),
5035 Builder.GetInsertBlock());
5036}
5037
5038llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5039 llvm::DIType *Ty) {
5040 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5041 if (CachedTy)
5042 Ty = CachedTy;
5043 return DBuilder.createObjectPointerType(Ty);
5044}
5045
5047 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5048 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5049 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5050 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5051
5052 if (Builder.GetInsertBlock() == nullptr)
5053 return;
5054 if (VD->hasAttr<NoDebugAttr>())
5055 return;
5056
5057 bool isByRef = VD->hasAttr<BlocksAttr>();
5058
5059 uint64_t XOffset = 0;
5060 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5061 llvm::DIType *Ty;
5062 if (isByRef)
5063 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5064 else
5065 Ty = getOrCreateType(VD->getType(), Unit);
5066
5067 // Self is passed along as an implicit non-arg variable in a
5068 // block. Mark it as the object pointer.
5069 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5070 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5071 Ty = CreateSelfType(VD->getType(), Ty);
5072
5073 // Get location information.
5074 const unsigned Line =
5075 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5076 unsigned Column = getColumnNumber(VD->getLocation());
5077
5078 const llvm::DataLayout &target = CGM.getDataLayout();
5079
5081 target.getStructLayout(blockInfo.StructureType)
5082 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5083
5085 addr.push_back(llvm::dwarf::DW_OP_deref);
5086 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5087 addr.push_back(offset.getQuantity());
5088 if (isByRef) {
5089 addr.push_back(llvm::dwarf::DW_OP_deref);
5090 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5091 // offset of __forwarding field
5092 offset =
5093 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5094 addr.push_back(offset.getQuantity());
5095 addr.push_back(llvm::dwarf::DW_OP_deref);
5096 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5097 // offset of x field
5098 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5099 addr.push_back(offset.getQuantity());
5100 }
5101
5102 // Create the descriptor for the variable.
5103 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5104 auto *D = DBuilder.createAutoVariable(
5105 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5106 Line, Ty, false, llvm::DINode::FlagZero, Align);
5107
5108 // Insert an llvm.dbg.declare into the current block.
5109 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5110 LexicalBlockStack.back(), CurInlinedAt);
5111 auto *Expr = DBuilder.createExpression(addr);
5112 if (InsertPoint)
5113 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
5114 else
5115 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5116}
5117
5118llvm::DILocalVariable *
5120 unsigned ArgNo, CGBuilderTy &Builder,
5121 bool UsePointerValue) {
5122 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5123 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5124}
5125
5126namespace {
5127struct BlockLayoutChunk {
5128 uint64_t OffsetInBits;
5130};
5131bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5132 return l.OffsetInBits < r.OffsetInBits;
5133}
5134} // namespace
5135
5136void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5137 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5138 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5140 // Blocks in OpenCL have unique constraints which make the standard fields
5141 // redundant while requiring size and align fields for enqueue_kernel. See
5142 // initializeForBlockHeader in CGBlocks.cpp
5143 if (CGM.getLangOpts().OpenCL) {
5144 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5145 BlockLayout.getElementOffsetInBits(0),
5146 Unit, Unit));
5147 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5148 BlockLayout.getElementOffsetInBits(1),
5149 Unit, Unit));
5150 } else {
5151 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5152 BlockLayout.getElementOffsetInBits(0),
5153 Unit, Unit));
5154 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5155 BlockLayout.getElementOffsetInBits(1),
5156 Unit, Unit));
5157 Fields.push_back(
5158 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5159 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5160 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5161 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5162 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5163 BlockLayout.getElementOffsetInBits(3),
5164 Unit, Unit));
5165 Fields.push_back(createFieldType(
5166 "__descriptor",
5167 Context.getPointerType(Block.NeedsCopyDispose
5169 : Context.getBlockDescriptorType()),
5170 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5171 }
5172}
5173
5175 StringRef Name,
5176 unsigned ArgNo,
5177 llvm::AllocaInst *Alloca,
5178 CGBuilderTy &Builder) {
5179 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5180 ASTContext &C = CGM.getContext();
5181 const BlockDecl *blockDecl = block.getBlockDecl();
5182
5183 // Collect some general information about the block's location.
5184 SourceLocation loc = blockDecl->getCaretLocation();
5185 llvm::DIFile *tunit = getOrCreateFile(loc);
5186 unsigned line = getLineNumber(loc);
5187 unsigned column = getColumnNumber(loc);
5188
5189 // Build the debug-info type for the block literal.
5190 getDeclContextDescriptor(blockDecl);
5191
5192 const llvm::StructLayout *blockLayout =
5193 CGM.getDataLayout().getStructLayout(block.StructureType);
5194
5196 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5197 fields);
5198
5199 // We want to sort the captures by offset, not because DWARF
5200 // requires this, but because we're paranoid about debuggers.
5202
5203 // 'this' capture.
5204 if (blockDecl->capturesCXXThis()) {
5205 BlockLayoutChunk chunk;
5206 chunk.OffsetInBits =
5207 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5208 chunk.Capture = nullptr;
5209 chunks.push_back(chunk);
5210 }
5211
5212 // Variable captures.
5213 for (const auto &capture : blockDecl->captures()) {
5214 const VarDecl *variable = capture.getVariable();
5215 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5216
5217 // Ignore constant captures.
5218 if (captureInfo.isConstant())
5219 continue;
5220
5221 BlockLayoutChunk chunk;
5222 chunk.OffsetInBits =
5223 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5224 chunk.Capture = &capture;
5225 chunks.push_back(chunk);
5226 }
5227
5228 // Sort by offset.
5229 llvm::array_pod_sort(chunks.begin(), chunks.end());
5230
5231 for (const BlockLayoutChunk &Chunk : chunks) {
5232 uint64_t offsetInBits = Chunk.OffsetInBits;
5233 const BlockDecl::Capture *capture = Chunk.Capture;
5234
5235 // If we have a null capture, this must be the C++ 'this' capture.
5236 if (!capture) {
5237 QualType type;
5238 if (auto *Method =
5239 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5240 type = Method->getThisType();
5241 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5242 type = QualType(RDecl->getTypeForDecl(), 0);
5243 else
5244 llvm_unreachable("unexpected block declcontext");
5245
5246 fields.push_back(createFieldType("this", type, loc, AS_public,
5247 offsetInBits, tunit, tunit));
5248 continue;
5249 }
5250
5251 const VarDecl *variable = capture->getVariable();
5252 StringRef name = variable->getName();
5253
5254 llvm::DIType *fieldType;
5255 if (capture->isByRef()) {
5256 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5257 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5258 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5259 uint64_t xoffset;
5260 fieldType =
5261 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5262 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5263 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5264 PtrInfo.Width, Align, offsetInBits,
5265 llvm::DINode::FlagZero, fieldType);
5266 } else {
5267 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5268 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5269 offsetInBits, Align, tunit, tunit);
5270 }
5271 fields.push_back(fieldType);
5272 }
5273
5274 SmallString<36> typeName;
5275 llvm::raw_svector_ostream(typeName)
5276 << "__block_literal_" << CGM.getUniqueBlockCount();
5277
5278 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5279
5280 llvm::DIType *type =
5281 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5282 CGM.getContext().toBits(block.BlockSize), 0,
5283 llvm::DINode::FlagZero, nullptr, fieldsArray);
5284 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5285