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