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