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