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