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