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