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