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