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