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