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