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