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