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