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