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