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