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