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