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