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