1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This coordinates the debug information generation while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/Basic/CodeGenOptions.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/FrontendOptions.h"
33 #include "clang/Lex/HeaderSearchOptions.h"
34 #include "clang/Lex/ModuleMap.h"
35 #include "clang/Lex/PreprocessorOptions.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/MD5.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/TimeProfiler.h"
50 using namespace clang;
51 using namespace clang::CodeGen;
53 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54 auto TI = Ctx.getTypeInfo(Ty);
55 return TI.AlignIsRequired ? TI.Align : 0;
58 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
62 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
66 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
67 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
68 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
69 DBuilder(CGM.getModule()) {
70 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
71 DebugPrefixMap[KV.first] = KV.second;
75 CGDebugInfo::~CGDebugInfo() {
76 assert(LexicalBlockStack.empty() &&
77 "Region stack mismatch, stack not empty!");
80 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
81 SourceLocation TemporaryLocation)
83 init(TemporaryLocation);
86 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
88 SourceLocation TemporaryLocation)
90 init(TemporaryLocation, DefaultToEmpty);
93 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
94 bool DefaultToEmpty) {
95 auto *DI = CGF->getDebugInfo();
101 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
103 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
106 if (TemporaryLocation.isValid()) {
107 DI->EmitLocation(CGF->Builder, TemporaryLocation);
111 if (DefaultToEmpty) {
112 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
116 // Construct a location that has a valid scope, but no line info.
117 assert(!DI->LexicalBlockStack.empty());
118 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
119 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
122 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
124 init(E->getExprLoc());
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
129 if (!CGF.getDebugInfo()) {
133 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
135 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
138 ApplyDebugLocation::~ApplyDebugLocation() {
139 // Query CGF so the location isn't overwritten when location updates are
140 // temporarily disabled (for C++ default function arguments)
142 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
145 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
146 GlobalDecl InlinedFn)
148 if (!CGF.getDebugInfo()) {
152 auto &DI = *CGF.getDebugInfo();
153 SavedLocation = DI.getLocation();
154 assert((DI.getInlinedAt() ==
155 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
156 "CGDebugInfo and IRBuilder are out of sync");
158 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
161 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
164 auto &DI = *CGF->getDebugInfo();
165 DI.EmitInlineFunctionEnd(CGF->Builder);
166 DI.EmitLocation(CGF->Builder, SavedLocation);
169 void CGDebugInfo::setLocation(SourceLocation Loc) {
170 // If the new location isn't valid return.
174 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
176 // If we've changed files in the middle of a lexical scope go ahead
177 // and create a new lexical scope with file node if it's different
178 // from the one in the scope.
179 if (LexicalBlockStack.empty())
182 SourceManager &SM = CGM.getContext().getSourceManager();
183 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
184 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
185 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
188 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
189 LexicalBlockStack.pop_back();
190 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
191 LBF->getScope(), getOrCreateFile(CurLoc)));
192 } else if (isa<llvm::DILexicalBlock>(Scope) ||
193 isa<llvm::DISubprogram>(Scope)) {
194 LexicalBlockStack.pop_back();
195 LexicalBlockStack.emplace_back(
196 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
200 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
201 llvm::DIScope *Mod = getParentModuleOrNull(D);
202 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
206 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
207 llvm::DIScope *Default) {
211 auto I = RegionMap.find(Context);
212 if (I != RegionMap.end()) {
213 llvm::Metadata *V = I->second;
214 return dyn_cast_or_null<llvm::DIScope>(V);
218 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
219 return getOrCreateNamespace(NSDecl);
221 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
222 if (!RDecl->isDependentType())
223 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
228 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
229 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
231 // If we're emitting codeview, it's important to try to match MSVC's naming so
232 // that visualizers written for MSVC will trigger for our class names. In
233 // particular, we can't have spaces between arguments of standard templates
234 // like basic_string and vector, but we must have spaces between consecutive
235 // angle brackets that close nested template argument lists.
236 if (CGM.getCodeGenOpts().EmitCodeView) {
237 PP.MSVCFormatting = true;
238 PP.SplitTemplateClosers = true;
240 // For DWARF, printing rules are underspecified.
241 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
242 PP.SplitTemplateClosers = true;
245 // Apply -fdebug-prefix-map.
246 PP.Callbacks = &PrintCB;
250 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
251 assert(FD && "Invalid FunctionDecl!");
252 IdentifierInfo *FII = FD->getIdentifier();
253 FunctionTemplateSpecializationInfo *Info =
254 FD->getTemplateSpecializationInfo();
256 // Emit the unqualified name in normal operation. LLVM and the debugger can
257 // compute the fully qualified name from the scope chain. If we're only
258 // emitting line table info, there won't be any scope chains, so emit the
259 // fully qualified name here so that stack traces are more accurate.
260 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
261 // evaluating the size impact.
262 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
263 CGM.getCodeGenOpts().EmitCodeView;
265 if (!Info && FII && !UseQualifiedName)
266 return FII->getName();
269 llvm::raw_svector_ostream OS(NS);
270 if (!UseQualifiedName)
273 FD->printQualifiedName(OS, getPrintingPolicy());
275 // Add any template specialization args.
277 const TemplateArgumentList *TArgs = Info->TemplateArguments;
278 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
281 // Copy this name on the side and use its reference.
282 return internString(OS.str());
285 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
286 SmallString<256> MethodName;
287 llvm::raw_svector_ostream OS(MethodName);
288 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
289 const DeclContext *DC = OMD->getDeclContext();
290 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
291 OS << OID->getName();
292 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
293 OS << OID->getName();
294 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
295 if (OC->IsClassExtension()) {
296 OS << OC->getClassInterface()->getName();
298 OS << OC->getIdentifier()->getNameStart() << '('
299 << OC->getIdentifier()->getNameStart() << ')';
301 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
302 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
304 OS << ' ' << OMD->getSelector().getAsString() << ']';
306 return internString(OS.str());
309 StringRef CGDebugInfo::getSelectorName(Selector S) {
310 return internString(S.getAsString());
313 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
314 if (isa<ClassTemplateSpecializationDecl>(RD)) {
315 SmallString<128> Name;
316 llvm::raw_svector_ostream OS(Name);
317 PrintingPolicy PP = getPrintingPolicy();
318 PP.PrintCanonicalTypes = true;
319 RD->getNameForDiagnostic(OS, PP,
320 /*Qualified*/ false);
322 // Copy this name on the side and use its reference.
323 return internString(Name);
326 // quick optimization to avoid having to intern strings that are already
327 // stored reliably elsewhere
328 if (const IdentifierInfo *II = RD->getIdentifier())
329 return II->getName();
331 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
332 // used to reconstruct the fully qualified type names.
333 if (CGM.getCodeGenOpts().EmitCodeView) {
334 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
335 assert(RD->getDeclContext() == D->getDeclContext() &&
336 "Typedef should not be in another decl context!");
337 assert(D->getDeclName().getAsIdentifierInfo() &&
338 "Typedef was not named!");
339 return D->getDeclName().getAsIdentifierInfo()->getName();
342 if (CGM.getLangOpts().CPlusPlus) {
345 ASTContext &Context = CGM.getContext();
346 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
347 // Anonymous types without a name for linkage purposes have their
348 // declarator mangled in if they have one.
349 Name = DD->getName();
350 else if (const TypedefNameDecl *TND =
351 Context.getTypedefNameForUnnamedTagDecl(RD))
352 // Anonymous types without a name for linkage purposes have their
353 // associate typedef mangled in if they have one.
354 Name = TND->getName();
357 SmallString<256> UnnamedType("<unnamed-type-");
360 return internString(UnnamedType);
368 Optional<llvm::DIFile::ChecksumKind>
369 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
372 if (!CGM.getCodeGenOpts().EmitCodeView &&
373 CGM.getCodeGenOpts().DwarfVersion < 5)
376 SourceManager &SM = CGM.getContext().getSourceManager();
378 const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
383 llvm::MD5::MD5Result Result;
385 Hash.update(MemBuffer->getBuffer());
388 Hash.stringifyResult(Result, Checksum);
389 return llvm::DIFile::CSK_MD5;
392 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
394 if (!CGM.getCodeGenOpts().EmbedSource)
397 bool SourceInvalid = false;
398 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
406 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
408 // If Location is not valid then use main input file.
409 return TheCU->getFile();
411 SourceManager &SM = CGM.getContext().getSourceManager();
412 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
414 StringRef FileName = PLoc.getFilename();
415 if (PLoc.isInvalid() || FileName.empty())
416 // If the location is not valid then use main input file.
417 return TheCU->getFile();
419 // Cache the results.
420 auto It = DIFileCache.find(FileName.data());
421 if (It != DIFileCache.end()) {
422 // Verify that the information still exists.
423 if (llvm::Metadata *V = It->second)
424 return cast<llvm::DIFile>(V);
427 SmallString<32> Checksum;
429 // Compute the checksum if possible. If the location is affected by a #line
430 // directive that refers to a file, PLoc will have an invalid FileID, and we
431 // will correctly get no checksum.
432 Optional<llvm::DIFile::ChecksumKind> CSKind =
433 computeChecksum(PLoc.getFileID(), Checksum);
434 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
436 CSInfo.emplace(*CSKind, Checksum);
437 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
441 CGDebugInfo::createFile(StringRef FileName,
442 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
443 Optional<StringRef> Source) {
446 std::string RemappedFile = remapDIPath(FileName);
447 std::string CurDir = remapDIPath(getCurrentDirname());
448 SmallString<128> DirBuf;
449 SmallString<128> FileBuf;
450 if (llvm::sys::path::is_absolute(RemappedFile)) {
451 // Strip the common prefix (if it is more than just "/") from current
452 // directory and FileName for a more space-efficient encoding.
453 auto FileIt = llvm::sys::path::begin(RemappedFile);
454 auto FileE = llvm::sys::path::end(RemappedFile);
455 auto CurDirIt = llvm::sys::path::begin(CurDir);
456 auto CurDirE = llvm::sys::path::end(CurDir);
457 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
458 llvm::sys::path::append(DirBuf, *CurDirIt);
459 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
460 // Don't strip the common prefix if it is only the root "/"
461 // since that would make LLVM diagnostic locations confusing.
465 for (; FileIt != FileE; ++FileIt)
466 llvm::sys::path::append(FileBuf, *FileIt);
474 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
475 DIFileCache[FileName.data()].reset(F);
479 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
480 if (DebugPrefixMap.empty())
483 SmallString<256> P = Path;
484 for (const auto &Entry : DebugPrefixMap)
485 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
487 return P.str().str();
490 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
491 if (Loc.isInvalid() && CurLoc.isInvalid())
493 SourceManager &SM = CGM.getContext().getSourceManager();
494 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
495 return PLoc.isValid() ? PLoc.getLine() : 0;
498 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
499 // We may not want column information at all.
500 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
503 // If the location is invalid then use the current column.
504 if (Loc.isInvalid() && CurLoc.isInvalid())
506 SourceManager &SM = CGM.getContext().getSourceManager();
507 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
508 return PLoc.isValid() ? PLoc.getColumn() : 0;
511 StringRef CGDebugInfo::getCurrentDirname() {
512 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
513 return CGM.getCodeGenOpts().DebugCompilationDir;
515 if (!CWDName.empty())
517 SmallString<256> CWD;
518 llvm::sys::fs::current_path(CWD);
519 return CWDName = internString(CWD);
522 void CGDebugInfo::CreateCompileUnit() {
523 SmallString<32> Checksum;
524 Optional<llvm::DIFile::ChecksumKind> CSKind;
525 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
527 // Should we be asking the SourceManager for the main file name, instead of
528 // accepting it as an argument? This just causes the main file name to
529 // mismatch with source locations and create extra lexical scopes or
530 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
531 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
532 // because that's what the SourceManager says)
534 // Get absolute path name.
535 SourceManager &SM = CGM.getContext().getSourceManager();
536 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
537 if (MainFileName.empty())
538 MainFileName = "<stdin>";
540 // The main file name provided via the "-main-file-name" option contains just
541 // the file name itself with no path information. This file name may have had
542 // a relative path, so we look into the actual file entry for the main
543 // file to determine the real absolute path for the file.
544 std::string MainFileDir;
545 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
546 MainFileDir = std::string(MainFile->getDir()->getName());
547 if (!llvm::sys::path::is_absolute(MainFileName)) {
548 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
549 llvm::sys::path::append(MainFileDirSS, MainFileName);
551 std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
553 // If the main file name provided is identical to the input file name, and
554 // if the input file is a preprocessed source, use the module name for
555 // debug info. The module name comes from the name specified in the first
556 // linemarker if the input is a preprocessed source.
557 if (MainFile->getName() == MainFileName &&
558 FrontendOptions::getInputKindForExtension(
559 MainFile->getName().rsplit('.').second)
561 MainFileName = CGM.getModule().getName().str();
563 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
566 llvm::dwarf::SourceLanguage LangTag;
567 const LangOptions &LO = CGM.getLangOpts();
570 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
571 else if (LO.CPlusPlus14)
572 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
573 else if (LO.CPlusPlus11)
574 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
576 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
577 } else if (LO.ObjC) {
578 LangTag = llvm::dwarf::DW_LANG_ObjC;
579 } else if (LO.RenderScript) {
580 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
582 LangTag = llvm::dwarf::DW_LANG_C99;
584 LangTag = llvm::dwarf::DW_LANG_C89;
587 std::string Producer = getClangFullVersion();
589 // Figure out which version of the ObjC runtime we have.
590 unsigned RuntimeVers = 0;
592 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
594 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
596 case codegenoptions::NoDebugInfo:
597 case codegenoptions::LocTrackingOnly:
598 EmissionKind = llvm::DICompileUnit::NoDebug;
600 case codegenoptions::DebugLineTablesOnly:
601 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
603 case codegenoptions::DebugDirectivesOnly:
604 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
606 case codegenoptions::DebugInfoConstructor:
607 case codegenoptions::LimitedDebugInfo:
608 case codegenoptions::FullDebugInfo:
609 EmissionKind = llvm::DICompileUnit::FullDebug;
614 auto &CGOpts = CGM.getCodeGenOpts();
615 // The DIFile used by the CU is distinct from the main source
616 // file. Its directory part specifies what becomes the
617 // DW_AT_comp_dir (the compilation directory), even if the source
618 // file was specified with an absolute path.
620 CSInfo.emplace(*CSKind, Checksum);
621 llvm::DIFile *CUFile = DBuilder.createFile(
622 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
623 getSource(SM, SM.getMainFileID()));
625 StringRef Sysroot, SDK;
626 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
627 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
628 auto B = llvm::sys::path::rbegin(Sysroot);
629 auto E = llvm::sys::path::rend(Sysroot);
630 auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
635 // Create new compile unit.
636 TheCU = DBuilder.createCompileUnit(
637 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
638 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
639 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
640 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
641 CGM.getTarget().getTriple().isNVPTX()
642 ? llvm::DICompileUnit::DebugNameTableKind::None
643 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
644 CGOpts.DebugNameTable),
645 CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
648 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
649 llvm::dwarf::TypeKind Encoding;
651 switch (BT->getKind()) {
652 #define BUILTIN_TYPE(Id, SingletonId)
653 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
654 #include "clang/AST/BuiltinTypes.def"
655 case BuiltinType::Dependent:
656 llvm_unreachable("Unexpected builtin type");
657 case BuiltinType::NullPtr:
658 return DBuilder.createNullPtrType();
659 case BuiltinType::Void:
661 case BuiltinType::ObjCClass:
664 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
665 "objc_class", TheCU, TheCU->getFile(), 0);
667 case BuiltinType::ObjCId: {
668 // typedef struct objc_class *Class;
669 // typedef struct objc_object {
678 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
679 "objc_class", TheCU, TheCU->getFile(), 0);
681 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
683 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
685 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
686 0, 0, llvm::DINode::FlagZero, nullptr,
687 llvm::DINodeArray());
689 DBuilder.replaceArrays(
690 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
691 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
692 llvm::DINode::FlagZero, ISATy)));
695 case BuiltinType::ObjCSel: {
697 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
698 "objc_selector", TheCU,
699 TheCU->getFile(), 0);
703 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
704 case BuiltinType::Id: \
705 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
707 #include "clang/Basic/OpenCLImageTypes.def"
708 case BuiltinType::OCLSampler:
709 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
710 case BuiltinType::OCLEvent:
711 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
712 case BuiltinType::OCLClkEvent:
713 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
714 case BuiltinType::OCLQueue:
715 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
716 case BuiltinType::OCLReserveID:
717 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
718 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
719 case BuiltinType::Id: \
720 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
721 #include "clang/Basic/OpenCLExtensionTypes.def"
723 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
724 #include "clang/Basic/AArch64SVEACLETypes.def"
726 ASTContext::BuiltinVectorTypeInfo Info =
727 CGM.getContext().getBuiltinVectorTypeInfo(BT);
728 unsigned NumElemsPerVG = (Info.EC.Min * Info.NumVectors) / 2;
730 // Debuggers can't extract 1bit from a vector, so will display a
731 // bitpattern for svbool_t instead.
732 if (Info.ElementType == CGM.getContext().BoolTy) {
734 Info.ElementType = CGM.getContext().UnsignedCharTy;
738 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
739 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
740 SmallVector<int64_t, 9> Expr(
741 {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
742 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
743 llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
744 auto *UpperBound = DBuilder.createExpression(Expr);
746 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
747 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
748 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
749 llvm::DIType *ElemTy =
750 getOrCreateType(Info.ElementType, TheCU->getFile());
751 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
752 return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
755 case BuiltinType::UChar:
756 case BuiltinType::Char_U:
757 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
759 case BuiltinType::Char_S:
760 case BuiltinType::SChar:
761 Encoding = llvm::dwarf::DW_ATE_signed_char;
763 case BuiltinType::Char8:
764 case BuiltinType::Char16:
765 case BuiltinType::Char32:
766 Encoding = llvm::dwarf::DW_ATE_UTF;
768 case BuiltinType::UShort:
769 case BuiltinType::UInt:
770 case BuiltinType::UInt128:
771 case BuiltinType::ULong:
772 case BuiltinType::WChar_U:
773 case BuiltinType::ULongLong:
774 Encoding = llvm::dwarf::DW_ATE_unsigned;
776 case BuiltinType::Short:
777 case BuiltinType::Int:
778 case BuiltinType::Int128:
779 case BuiltinType::Long:
780 case BuiltinType::WChar_S:
781 case BuiltinType::LongLong:
782 Encoding = llvm::dwarf::DW_ATE_signed;
784 case BuiltinType::Bool:
785 Encoding = llvm::dwarf::DW_ATE_boolean;
787 case BuiltinType::Half:
788 case BuiltinType::Float:
789 case BuiltinType::LongDouble:
790 case BuiltinType::Float16:
791 case BuiltinType::BFloat16:
792 case BuiltinType::Float128:
793 case BuiltinType::Double:
794 // FIXME: For targets where long double and __float128 have the same size,
795 // they are currently indistinguishable in the debugger without some
796 // special treatment. However, there is currently no consensus on encoding
797 // and this should be updated once a DWARF encoding exists for distinct
798 // floating point types of the same size.
799 Encoding = llvm::dwarf::DW_ATE_float;
801 case BuiltinType::ShortAccum:
802 case BuiltinType::Accum:
803 case BuiltinType::LongAccum:
804 case BuiltinType::ShortFract:
805 case BuiltinType::Fract:
806 case BuiltinType::LongFract:
807 case BuiltinType::SatShortFract:
808 case BuiltinType::SatFract:
809 case BuiltinType::SatLongFract:
810 case BuiltinType::SatShortAccum:
811 case BuiltinType::SatAccum:
812 case BuiltinType::SatLongAccum:
813 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
815 case BuiltinType::UShortAccum:
816 case BuiltinType::UAccum:
817 case BuiltinType::ULongAccum:
818 case BuiltinType::UShortFract:
819 case BuiltinType::UFract:
820 case BuiltinType::ULongFract:
821 case BuiltinType::SatUShortAccum:
822 case BuiltinType::SatUAccum:
823 case BuiltinType::SatULongAccum:
824 case BuiltinType::SatUShortFract:
825 case BuiltinType::SatUFract:
826 case BuiltinType::SatULongFract:
827 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
831 switch (BT->getKind()) {
832 case BuiltinType::Long:
835 case BuiltinType::LongLong:
836 BTName = "long long int";
838 case BuiltinType::ULong:
839 BTName = "long unsigned int";
841 case BuiltinType::ULongLong:
842 BTName = "long long unsigned int";
845 BTName = BT->getName(CGM.getLangOpts());
848 // Bit size and offset of the type.
849 uint64_t Size = CGM.getContext().getTypeSize(BT);
850 return DBuilder.createBasicType(BTName, Size, Encoding);
853 llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
854 return DBuilder.createUnspecifiedType("auto");
857 llvm::DIType *CGDebugInfo::CreateType(const ExtIntType *Ty) {
859 StringRef Name = Ty->isUnsigned() ? "unsigned _ExtInt" : "_ExtInt";
860 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
861 ? llvm::dwarf::DW_ATE_unsigned
862 : llvm::dwarf::DW_ATE_signed;
864 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
868 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
869 // Bit size and offset of the type.
870 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
871 if (Ty->isComplexIntegerType())
872 Encoding = llvm::dwarf::DW_ATE_lo_user;
874 uint64_t Size = CGM.getContext().getTypeSize(Ty);
875 return DBuilder.createBasicType("complex", Size, Encoding);
878 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
879 llvm::DIFile *Unit) {
880 QualifierCollector Qc;
881 const Type *T = Qc.strip(Ty);
883 // Ignore these qualifiers for now.
884 Qc.removeObjCGCAttr();
885 Qc.removeAddressSpace();
886 Qc.removeObjCLifetime();
888 // We will create one Derived type for one qualifier and recurse to handle any
890 llvm::dwarf::Tag Tag;
892 Tag = llvm::dwarf::DW_TAG_const_type;
894 } else if (Qc.hasVolatile()) {
895 Tag = llvm::dwarf::DW_TAG_volatile_type;
897 } else if (Qc.hasRestrict()) {
898 Tag = llvm::dwarf::DW_TAG_restrict_type;
901 assert(Qc.empty() && "Unknown type qualifier for debug info");
902 return getOrCreateType(QualType(T, 0), Unit);
905 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
907 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
908 // CVR derived types.
909 return DBuilder.createQualifiedType(Tag, FromTy);
912 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
913 llvm::DIFile *Unit) {
915 // The frontend treats 'id' as a typedef to an ObjCObjectType,
916 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
917 // debug info, we want to emit 'id' in both cases.
918 if (Ty->isObjCQualifiedIdType())
919 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
921 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
922 Ty->getPointeeType(), Unit);
925 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
926 llvm::DIFile *Unit) {
927 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
928 Ty->getPointeeType(), Unit);
931 /// \return whether a C++ mangling exists for the type defined by TD.
932 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
933 switch (TheCU->getSourceLanguage()) {
934 case llvm::dwarf::DW_LANG_C_plus_plus:
935 case llvm::dwarf::DW_LANG_C_plus_plus_11:
936 case llvm::dwarf::DW_LANG_C_plus_plus_14:
938 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
939 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
945 // Determines if the debug info for this tag declaration needs a type
946 // identifier. The purpose of the unique identifier is to deduplicate type
947 // information for identical types across TUs. Because of the C++ one definition
948 // rule (ODR), it is valid to assume that the type is defined the same way in
949 // every TU and its debug info is equivalent.
951 // C does not have the ODR, and it is common for codebases to contain multiple
952 // different definitions of a struct with the same name in different TUs.
953 // Therefore, if the type doesn't have a C++ mangling, don't give it an
954 // identifer. Type information in C is smaller and simpler than C++ type
955 // information, so the increase in debug info size is negligible.
957 // If the type is not externally visible, it should be unique to the current TU,
958 // and should not need an identifier to participate in type deduplication.
959 // However, when emitting CodeView, the format internally uses these
960 // unique type name identifers for references between debug info. For example,
961 // the method of a class in an anonymous namespace uses the identifer to refer
962 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
963 // for such types, so when emitting CodeView, always use identifiers for C++
964 // types. This may create problems when attempting to emit CodeView when the MS
965 // C++ ABI is not in use.
966 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
967 llvm::DICompileUnit *TheCU) {
968 // We only add a type identifier for types with C++ name mangling.
969 if (!hasCXXMangling(TD, TheCU))
972 // Externally visible types with C++ mangling need a type identifier.
973 if (TD->isExternallyVisible())
976 // CodeView types with C++ mangling need a type identifier.
977 if (CGM.getCodeGenOpts().EmitCodeView)
983 // Returns a unique type identifier string if one exists, or an empty string.
984 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
985 llvm::DICompileUnit *TheCU) {
986 SmallString<256> Identifier;
987 const TagDecl *TD = Ty->getDecl();
989 if (!needsTypeIdentifier(TD, CGM, TheCU))
991 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
992 if (RD->getDefinition())
993 if (RD->isDynamicClass() &&
994 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
997 // TODO: This is using the RTTI name. Is there a better way to get
998 // a unique string for a type?
999 llvm::raw_svector_ostream Out(Identifier);
1000 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1004 /// \return the appropriate DWARF tag for a composite type.
1005 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1006 llvm::dwarf::Tag Tag;
1007 if (RD->isStruct() || RD->isInterface())
1008 Tag = llvm::dwarf::DW_TAG_structure_type;
1009 else if (RD->isUnion())
1010 Tag = llvm::dwarf::DW_TAG_union_type;
1012 // FIXME: This could be a struct type giving a default visibility different
1013 // than C++ class type, but needs llvm metadata changes first.
1014 assert(RD->isClass());
1015 Tag = llvm::dwarf::DW_TAG_class_type;
1020 llvm::DICompositeType *
1021 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1022 llvm::DIScope *Ctx) {
1023 const RecordDecl *RD = Ty->getDecl();
1024 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1025 return cast<llvm::DICompositeType>(T);
1026 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1027 unsigned Line = getLineNumber(RD->getLocation());
1028 StringRef RDName = getClassName(RD);
1033 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1035 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1036 // add the flag if a record has no definition because we don't know whether
1037 // it will be trivial or not.
1038 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1039 if (!CXXRD->hasDefinition() ||
1040 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1041 Flags |= llvm::DINode::FlagNonTrivial;
1044 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1045 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1046 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1048 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1049 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1050 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1051 CollectCXXTemplateParams(TSpecial, DefUnit));
1052 ReplaceMap.emplace_back(
1053 std::piecewise_construct, std::make_tuple(Ty),
1054 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1058 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1061 llvm::DIFile *Unit) {
1062 // Bit size, align and offset of the type.
1063 // Size is always the size of a pointer. We can't use getTypeSize here
1064 // because that does not return the correct value for references.
1065 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1066 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1067 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1068 Optional<unsigned> DWARFAddressSpace =
1069 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1071 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1072 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1073 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1074 Size, Align, DWARFAddressSpace);
1076 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1077 Align, DWARFAddressSpace);
1080 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1081 llvm::DIType *&Cache) {
1084 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1085 TheCU, TheCU->getFile(), 0);
1086 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1087 Cache = DBuilder.createPointerType(Cache, Size);
1091 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1092 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1093 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1096 // Advanced by calls to CreateMemberType in increments of FType, then
1097 // returned as the overall size of the default elements.
1098 uint64_t FieldOffset = 0;
1100 // Blocks in OpenCL have unique constraints which make the standard fields
1101 // redundant while requiring size and align fields for enqueue_kernel. See
1102 // initializeForBlockHeader in CGBlocks.cpp
1103 if (CGM.getLangOpts().OpenCL) {
1104 FType = CGM.getContext().IntTy;
1105 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1106 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1108 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1109 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1110 FType = CGM.getContext().IntTy;
1111 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1112 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1113 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1114 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1115 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1116 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1117 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1118 EltTys.push_back(DBuilder.createMemberType(
1119 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1120 FieldOffset, llvm::DINode::FlagZero, DescTy));
1121 FieldOffset += FieldSize;
1127 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1128 llvm::DIFile *Unit) {
1129 SmallVector<llvm::Metadata *, 8> EltTys;
1131 uint64_t FieldOffset;
1132 llvm::DINodeArray Elements;
1135 FType = CGM.getContext().UnsignedLongTy;
1136 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1137 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1139 Elements = DBuilder.getOrCreateArray(EltTys);
1142 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1145 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1146 FieldOffset, 0, Flags, nullptr, Elements);
1148 // Bit size, align and offset of the type.
1149 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1151 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1153 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1156 Elements = DBuilder.getOrCreateArray(EltTys);
1158 // The __block_literal_generic structs are marked with a special
1159 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1160 // the debugger needs to know about. To allow type uniquing, emit
1161 // them without a name or a location.
1162 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1163 Flags, nullptr, Elements);
1165 return DBuilder.createPointerType(EltTy, Size);
1168 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1169 llvm::DIFile *Unit) {
1170 assert(Ty->isTypeAlias());
1171 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1174 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1175 ->getTemplatedDecl();
1177 if (AliasDecl->hasAttr<NoDebugAttr>())
1180 SmallString<128> NS;
1181 llvm::raw_svector_ostream OS(NS);
1182 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1183 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1185 SourceLocation Loc = AliasDecl->getLocation();
1186 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1188 getDeclContextDescriptor(AliasDecl));
1191 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1192 llvm::DIFile *Unit) {
1193 llvm::DIType *Underlying =
1194 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1196 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1199 // We don't set size information, but do specify where the typedef was
1201 SourceLocation Loc = Ty->getDecl()->getLocation();
1203 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1204 // Typedefs are derived from some other type.
1205 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1206 getOrCreateFile(Loc), getLineNumber(Loc),
1207 getDeclContextDescriptor(Ty->getDecl()), Align);
1210 static unsigned getDwarfCC(CallingConv CC) {
1213 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1217 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1218 case CC_X86FastCall:
1219 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1220 case CC_X86ThisCall:
1221 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1222 case CC_X86VectorCall:
1223 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1225 return llvm::dwarf::DW_CC_BORLAND_pascal;
1227 return llvm::dwarf::DW_CC_LLVM_Win64;
1229 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1231 case CC_AArch64VectorCall:
1232 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1234 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1235 case CC_IntelOclBicc:
1236 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1237 case CC_SpirFunction:
1238 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1239 case CC_OpenCLKernel:
1240 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1242 return llvm::dwarf::DW_CC_LLVM_Swift;
1243 case CC_PreserveMost:
1244 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1245 case CC_PreserveAll:
1246 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1248 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1253 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1254 llvm::DIFile *Unit) {
1255 SmallVector<llvm::Metadata *, 16> EltTys;
1257 // Add the result type at least.
1258 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1260 // Set up remainder of arguments if there is a prototype.
1261 // otherwise emit it as a variadic function.
1262 if (isa<FunctionNoProtoType>(Ty))
1263 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1264 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1265 for (const QualType &ParamType : FPT->param_types())
1266 EltTys.push_back(getOrCreateType(ParamType, Unit));
1267 if (FPT->isVariadic())
1268 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1271 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1272 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1273 getDwarfCC(Ty->getCallConv()));
1276 /// Convert an AccessSpecifier into the corresponding DINode flag.
1277 /// As an optimization, return 0 if the access specifier equals the
1278 /// default for the containing type.
1279 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1280 const RecordDecl *RD) {
1281 AccessSpecifier Default = clang::AS_none;
1282 if (RD && RD->isClass())
1283 Default = clang::AS_private;
1284 else if (RD && (RD->isStruct() || RD->isUnion()))
1285 Default = clang::AS_public;
1287 if (Access == Default)
1288 return llvm::DINode::FlagZero;
1291 case clang::AS_private:
1292 return llvm::DINode::FlagPrivate;
1293 case clang::AS_protected:
1294 return llvm::DINode::FlagProtected;
1295 case clang::AS_public:
1296 return llvm::DINode::FlagPublic;
1297 case clang::AS_none:
1298 return llvm::DINode::FlagZero;
1300 llvm_unreachable("unexpected access enumerator");
1303 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1304 llvm::DIScope *RecordTy,
1305 const RecordDecl *RD) {
1306 StringRef Name = BitFieldDecl->getName();
1307 QualType Ty = BitFieldDecl->getType();
1308 SourceLocation Loc = BitFieldDecl->getLocation();
1309 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1310 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1312 // Get the location for the field.
1313 llvm::DIFile *File = getOrCreateFile(Loc);
1314 unsigned Line = getLineNumber(Loc);
1316 const CGBitFieldInfo &BitFieldInfo =
1317 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1318 uint64_t SizeInBits = BitFieldInfo.Size;
1319 assert(SizeInBits > 0 && "found named 0-width bitfield");
1320 uint64_t StorageOffsetInBits =
1321 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1322 uint64_t Offset = BitFieldInfo.Offset;
1323 // The bit offsets for big endian machines are reversed for big
1324 // endian target, compensate for that as the DIDerivedType requires
1325 // un-reversed offsets.
1326 if (CGM.getDataLayout().isBigEndian())
1327 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1328 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1329 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1330 return DBuilder.createBitFieldMemberType(
1331 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1336 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1337 AccessSpecifier AS, uint64_t offsetInBits,
1338 uint32_t AlignInBits, llvm::DIFile *tunit,
1339 llvm::DIScope *scope, const RecordDecl *RD) {
1340 llvm::DIType *debugType = getOrCreateType(type, tunit);
1342 // Get the location for the field.
1343 llvm::DIFile *file = getOrCreateFile(loc);
1344 unsigned line = getLineNumber(loc);
1346 uint64_t SizeInBits = 0;
1347 auto Align = AlignInBits;
1348 if (!type->isIncompleteArrayType()) {
1349 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1350 SizeInBits = TI.Width;
1352 Align = getTypeAlignIfRequired(type, CGM.getContext());
1355 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1356 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1357 offsetInBits, flags, debugType);
1360 void CGDebugInfo::CollectRecordLambdaFields(
1361 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1362 llvm::DIType *RecordTy) {
1363 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1364 // has the name and the location of the variable so we should iterate over
1365 // both concurrently.
1366 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1367 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1368 unsigned fieldno = 0;
1369 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1370 E = CXXDecl->captures_end();
1371 I != E; ++I, ++Field, ++fieldno) {
1372 const LambdaCapture &C = *I;
1373 if (C.capturesVariable()) {
1374 SourceLocation Loc = C.getLocation();
1375 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1376 VarDecl *V = C.getCapturedVar();
1377 StringRef VName = V->getName();
1378 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1379 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1380 llvm::DIType *FieldType = createFieldType(
1381 VName, Field->getType(), Loc, Field->getAccess(),
1382 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1383 elements.push_back(FieldType);
1384 } else if (C.capturesThis()) {
1385 // TODO: Need to handle 'this' in some way by probably renaming the
1386 // this of the lambda class and having a field member of 'this' or
1387 // by using AT_object_pointer for the function and having that be
1388 // used as 'this' for semantic references.
1389 FieldDecl *f = *Field;
1390 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1391 QualType type = f->getType();
1392 llvm::DIType *fieldType = createFieldType(
1393 "this", type, f->getLocation(), f->getAccess(),
1394 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1396 elements.push_back(fieldType);
1401 llvm::DIDerivedType *
1402 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1403 const RecordDecl *RD) {
1404 // Create the descriptor for the static variable, with or without
1405 // constant initializers.
1406 Var = Var->getCanonicalDecl();
1407 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1408 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1410 unsigned LineNumber = getLineNumber(Var->getLocation());
1411 StringRef VName = Var->getName();
1412 llvm::Constant *C = nullptr;
1413 if (Var->getInit()) {
1414 const APValue *Value = Var->evaluateValue();
1417 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1418 if (Value->isFloat())
1419 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1423 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1424 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1425 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1426 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1427 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1431 void CGDebugInfo::CollectRecordNormalField(
1432 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1433 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1434 const RecordDecl *RD) {
1435 StringRef name = field->getName();
1436 QualType type = field->getType();
1438 // Ignore unnamed fields unless they're anonymous structs/unions.
1439 if (name.empty() && !type->isRecordType())
1442 llvm::DIType *FieldType;
1443 if (field->isBitField()) {
1444 FieldType = createBitFieldType(field, RecordTy, RD);
1446 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1448 createFieldType(name, type, field->getLocation(), field->getAccess(),
1449 OffsetInBits, Align, tunit, RecordTy, RD);
1452 elements.push_back(FieldType);
1455 void CGDebugInfo::CollectRecordNestedType(
1456 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1457 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1458 // Injected class names are not considered nested records.
1459 if (isa<InjectedClassNameType>(Ty))
1461 SourceLocation Loc = TD->getLocation();
1462 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1463 elements.push_back(nestedType);
1466 void CGDebugInfo::CollectRecordFields(
1467 const RecordDecl *record, llvm::DIFile *tunit,
1468 SmallVectorImpl<llvm::Metadata *> &elements,
1469 llvm::DICompositeType *RecordTy) {
1470 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1472 if (CXXDecl && CXXDecl->isLambda())
1473 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1475 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1477 // Field number for non-static fields.
1478 unsigned fieldNo = 0;
1480 // Static and non-static members should appear in the same order as
1481 // the corresponding declarations in the source program.
1482 for (const auto *I : record->decls())
1483 if (const auto *V = dyn_cast<VarDecl>(I)) {
1484 if (V->hasAttr<NoDebugAttr>())
1487 // Skip variable template specializations when emitting CodeView. MSVC
1488 // doesn't emit them.
1489 if (CGM.getCodeGenOpts().EmitCodeView &&
1490 isa<VarTemplateSpecializationDecl>(V))
1493 if (isa<VarTemplatePartialSpecializationDecl>(V))
1496 // Reuse the existing static member declaration if one exists
1497 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1498 if (MI != StaticDataMemberCache.end()) {
1499 assert(MI->second &&
1500 "Static data member declaration should still exist");
1501 elements.push_back(MI->second);
1503 auto Field = CreateRecordStaticField(V, RecordTy, record);
1504 elements.push_back(Field);
1506 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1507 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1508 elements, RecordTy, record);
1510 // Bump field number for next field.
1512 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1513 // Debug info for nested types is included in the member list only for
1515 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1516 if (!nestedType->isImplicit() &&
1517 nestedType->getDeclContext() == record)
1518 CollectRecordNestedType(nestedType, elements);
1523 llvm::DISubroutineType *
1524 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1525 llvm::DIFile *Unit, bool decl) {
1526 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1527 if (Method->isStatic())
1528 return cast_or_null<llvm::DISubroutineType>(
1529 getOrCreateType(QualType(Func, 0), Unit));
1530 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1533 llvm::DISubroutineType *
1534 CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1535 const FunctionProtoType *Func,
1536 llvm::DIFile *Unit, bool decl) {
1537 // Add "this" pointer.
1538 llvm::DITypeRefArray Args(
1539 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1541 assert(Args.size() && "Invalid number of arguments!");
1543 SmallVector<llvm::Metadata *, 16> Elts;
1544 // First element is always return type. For 'void' functions it is NULL.
1545 QualType temp = Func->getReturnType();
1546 if (temp->getTypeClass() == Type::Auto && decl)
1547 Elts.push_back(CreateType(cast<AutoType>(temp)));
1549 Elts.push_back(Args[0]);
1551 // "this" pointer is always first argument.
1552 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1553 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1554 // Create pointer type directly in this case.
1555 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1556 QualType PointeeTy = ThisPtrTy->getPointeeType();
1557 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1558 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1559 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1560 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1561 llvm::DIType *ThisPtrType =
1562 DBuilder.createPointerType(PointeeType, Size, Align);
1563 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1564 // TODO: This and the artificial type below are misleading, the
1565 // types aren't artificial the argument is, but the current
1566 // metadata doesn't represent that.
1567 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1568 Elts.push_back(ThisPtrType);
1570 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1571 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1572 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1573 Elts.push_back(ThisPtrType);
1576 // Copy rest of the arguments.
1577 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1578 Elts.push_back(Args[i]);
1580 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1582 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1583 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1584 Flags |= llvm::DINode::FlagLValueReference;
1585 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1586 Flags |= llvm::DINode::FlagRValueReference;
1588 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1589 getDwarfCC(Func->getCallConv()));
1592 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1593 /// inside a function.
1594 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1595 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1596 return isFunctionLocalClass(NRD);
1597 if (isa<FunctionDecl>(RD->getDeclContext()))
1602 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1603 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1605 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1607 StringRef MethodName = getFunctionName(Method);
1608 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1610 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1611 // make sense to give a single ctor/dtor a linkage name.
1612 StringRef MethodLinkageName;
1613 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1614 // property to use here. It may've been intended to model "is non-external
1615 // type" but misses cases of non-function-local but non-external classes such
1616 // as those in anonymous namespaces as well as the reverse - external types
1617 // that are function local, such as those in (non-local) inline functions.
1618 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1619 MethodLinkageName = CGM.getMangledName(Method);
1621 // Get the location for the method.
1622 llvm::DIFile *MethodDefUnit = nullptr;
1623 unsigned MethodLine = 0;
1624 if (!Method->isImplicit()) {
1625 MethodDefUnit = getOrCreateFile(Method->getLocation());
1626 MethodLine = getLineNumber(Method->getLocation());
1629 // Collect virtual method info.
1630 llvm::DIType *ContainingType = nullptr;
1631 unsigned VIndex = 0;
1632 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1633 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1634 int ThisAdjustment = 0;
1636 if (Method->isVirtual()) {
1637 if (Method->isPure())
1638 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1640 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1642 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1643 // It doesn't make sense to give a virtual destructor a vtable index,
1644 // since a single destructor has two entries in the vtable.
1645 if (!isa<CXXDestructorDecl>(Method))
1646 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1648 // Emit MS ABI vftable information. There is only one entry for the
1650 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1651 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1652 MethodVFTableLocation ML =
1653 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1656 // CodeView only records the vftable offset in the class that introduces
1657 // the virtual method. This is possible because, unlike Itanium, the MS
1658 // C++ ABI does not include all virtual methods from non-primary bases in
1659 // the vtable for the most derived class. For example, if C inherits from
1660 // A and B, C's primary vftable will not include B's virtual methods.
1661 if (Method->size_overridden_methods() == 0)
1662 Flags |= llvm::DINode::FlagIntroducedVirtual;
1664 // The 'this' adjustment accounts for both the virtual and non-virtual
1665 // portions of the adjustment. Presumably the debugger only uses it when
1666 // it knows the dynamic type of an object.
1667 ThisAdjustment = CGM.getCXXABI()
1668 .getVirtualFunctionPrologueThisAdjustment(GD)
1671 ContainingType = RecordTy;
1674 // We're checking for deleted C++ special member functions
1675 // [Ctors,Dtors, Copy/Move]
1676 auto checkAttrDeleted = [&](const auto *Method) {
1677 if (Method->getCanonicalDecl()->isDeleted())
1678 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1681 switch (Method->getKind()) {
1683 case Decl::CXXConstructor:
1684 case Decl::CXXDestructor:
1685 checkAttrDeleted(Method);
1687 case Decl::CXXMethod:
1688 if (Method->isCopyAssignmentOperator() ||
1689 Method->isMoveAssignmentOperator())
1690 checkAttrDeleted(Method);
1696 if (Method->isNoReturn())
1697 Flags |= llvm::DINode::FlagNoReturn;
1699 if (Method->isStatic())
1700 Flags |= llvm::DINode::FlagStaticMember;
1701 if (Method->isImplicit())
1702 Flags |= llvm::DINode::FlagArtificial;
1703 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1704 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1705 if (CXXC->isExplicit())
1706 Flags |= llvm::DINode::FlagExplicit;
1707 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1708 if (CXXC->isExplicit())
1709 Flags |= llvm::DINode::FlagExplicit;
1711 if (Method->hasPrototype())
1712 Flags |= llvm::DINode::FlagPrototyped;
1713 if (Method->getRefQualifier() == RQ_LValue)
1714 Flags |= llvm::DINode::FlagLValueReference;
1715 if (Method->getRefQualifier() == RQ_RValue)
1716 Flags |= llvm::DINode::FlagRValueReference;
1717 if (CGM.getLangOpts().Optimize)
1718 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1720 // In this debug mode, emit type info for a class when its constructor type
1722 if (DebugKind == codegenoptions::DebugInfoConstructor)
1723 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1724 completeClass(CD->getParent());
1726 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1727 llvm::DISubprogram *SP = DBuilder.createMethod(
1728 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1729 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1730 TParamsArray.get());
1732 SPCache[Method->getCanonicalDecl()].reset(SP);
1737 void CGDebugInfo::CollectCXXMemberFunctions(
1738 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1739 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1741 // Since we want more than just the individual member decls if we
1742 // have templated functions iterate over every declaration to gather
1744 for (const auto *I : RD->decls()) {
1745 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1746 // If the member is implicit, don't add it to the member list. This avoids
1747 // the member being added to type units by LLVM, while still allowing it
1748 // to be emitted into the type declaration/reference inside the compile
1750 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1751 // FIXME: Handle Using(Shadow?)Decls here to create
1752 // DW_TAG_imported_declarations inside the class for base decls brought into
1753 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1754 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1756 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1759 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1762 // Reuse the existing member function declaration if it exists.
1763 // It may be associated with the declaration of the type & should be
1764 // reused as we're building the definition.
1766 // This situation can arise in the vtable-based debug info reduction where
1767 // implicit members are emitted in a non-vtable TU.
1768 auto MI = SPCache.find(Method->getCanonicalDecl());
1769 EltTys.push_back(MI == SPCache.end()
1770 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1771 : static_cast<llvm::Metadata *>(MI->second));
1775 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1776 SmallVectorImpl<llvm::Metadata *> &EltTys,
1777 llvm::DIType *RecordTy) {
1778 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1779 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1780 llvm::DINode::FlagZero);
1782 // If we are generating CodeView debug info, we also need to emit records for
1783 // indirect virtual base classes.
1784 if (CGM.getCodeGenOpts().EmitCodeView) {
1785 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1786 llvm::DINode::FlagIndirectVirtualBase);
1790 void CGDebugInfo::CollectCXXBasesAux(
1791 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1792 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1793 const CXXRecordDecl::base_class_const_range &Bases,
1794 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1795 llvm::DINode::DIFlags StartingFlags) {
1796 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1797 for (const auto &BI : Bases) {
1799 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1800 if (!SeenTypes.insert(Base).second)
1802 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1803 llvm::DINode::DIFlags BFlags = StartingFlags;
1804 uint64_t BaseOffset;
1805 uint32_t VBPtrOffset = 0;
1807 if (BI.isVirtual()) {
1808 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1809 // virtual base offset offset is -ve. The code generator emits dwarf
1810 // expression where it expects +ve number.
1811 BaseOffset = 0 - CGM.getItaniumVTableContext()
1812 .getVirtualBaseOffsetOffset(RD, Base)
1815 // In the MS ABI, store the vbtable offset, which is analogous to the
1816 // vbase offset offset in Itanium.
1818 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1819 VBPtrOffset = CGM.getContext()
1820 .getASTRecordLayout(RD)
1824 BFlags |= llvm::DINode::FlagVirtual;
1826 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1827 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1828 // BI->isVirtual() and bits when not.
1830 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1831 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1832 VBPtrOffset, BFlags);
1833 EltTys.push_back(DTy);
1838 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1839 ArrayRef<TemplateArgument> TAList,
1840 llvm::DIFile *Unit) {
1841 SmallVector<llvm::Metadata *, 16> TemplateParams;
1842 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1843 const TemplateArgument &TA = TAList[i];
1845 bool defaultParameter = false;
1847 Name = TPList->getParam(i)->getName();
1848 switch (TA.getKind()) {
1849 case TemplateArgument::Type: {
1850 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1853 if (auto *templateType =
1854 dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1855 if (templateType->hasDefaultArgument())
1857 templateType->getDefaultArgument() == TA.getAsType();
1859 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1860 TheCU, Name, TTy, defaultParameter));
1863 case TemplateArgument::Integral: {
1864 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1865 if (TPList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1866 if (auto *templateType =
1867 dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
1868 if (templateType->hasDefaultArgument() &&
1869 !templateType->getDefaultArgument()->isValueDependent())
1870 defaultParameter = llvm::APSInt::isSameValue(
1871 templateType->getDefaultArgument()->EvaluateKnownConstInt(
1873 TA.getAsIntegral());
1875 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1876 TheCU, Name, TTy, defaultParameter,
1877 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1879 case TemplateArgument::Declaration: {
1880 const ValueDecl *D = TA.getAsDecl();
1881 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1882 llvm::DIType *TTy = getOrCreateType(T, Unit);
1883 llvm::Constant *V = nullptr;
1884 // Skip retrieve the value if that template parameter has cuda device
1885 // attribute, i.e. that value is not available at the host side.
1886 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1887 !D->hasAttr<CUDADeviceAttr>()) {
1888 const CXXMethodDecl *MD;
1889 // Variable pointer template parameters have a value that is the address
1891 if (const auto *VD = dyn_cast<VarDecl>(D))
1892 V = CGM.GetAddrOfGlobalVar(VD);
1893 // Member function pointers have special support for building them,
1894 // though this is currently unsupported in LLVM CodeGen.
1895 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1896 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1897 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1898 V = CGM.GetAddrOfFunction(FD);
1899 // Member data pointers have special handling too to compute the fixed
1900 // offset within the object.
1901 else if (const auto *MPT =
1902 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1903 // These five lines (& possibly the above member function pointer
1904 // handling) might be able to be refactored to use similar code in
1905 // CodeGenModule::getMemberPointerConstant
1906 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1908 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1909 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1910 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
1911 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
1913 assert(V && "Failed to find template parameter pointer");
1914 V = V->stripPointerCasts();
1916 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1917 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
1919 case TemplateArgument::NullPtr: {
1920 QualType T = TA.getNullPtrType();
1921 llvm::DIType *TTy = getOrCreateType(T, Unit);
1922 llvm::Constant *V = nullptr;
1923 // Special case member data pointer null values since they're actually -1
1925 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1926 // But treat member function pointers as simple zero integers because
1927 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1928 // CodeGen grows handling for values of non-null member function
1929 // pointers then perhaps we could remove this special case and rely on
1930 // EmitNullMemberPointer for member function pointers.
1931 if (MPT->isMemberDataPointer())
1932 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1934 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1935 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1936 TheCU, Name, TTy, defaultParameter, V));
1938 case TemplateArgument::Template:
1939 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1940 TheCU, Name, nullptr,
1941 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1943 case TemplateArgument::Pack:
1944 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1945 TheCU, Name, nullptr,
1946 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1948 case TemplateArgument::Expression: {
1949 const Expr *E = TA.getAsExpr();
1950 QualType T = E->getType();
1952 T = CGM.getContext().getLValueReferenceType(T);
1953 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1954 assert(V && "Expression in template argument isn't constant");
1955 llvm::DIType *TTy = getOrCreateType(T, Unit);
1956 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1957 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
1959 // And the following should never occur:
1960 case TemplateArgument::TemplateExpansion:
1961 case TemplateArgument::Null:
1963 "These argument types shouldn't exist in concrete types");
1966 return DBuilder.getOrCreateArray(TemplateParams);
1970 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1971 llvm::DIFile *Unit) {
1972 if (FD->getTemplatedKind() ==
1973 FunctionDecl::TK_FunctionTemplateSpecialization) {
1974 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1976 ->getTemplateParameters();
1977 return CollectTemplateParams(
1978 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1980 return llvm::DINodeArray();
1983 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
1984 llvm::DIFile *Unit) {
1985 // Always get the full list of parameters, not just the ones from the
1986 // specialization. A partial specialization may have fewer parameters than
1987 // there are arguments.
1988 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1990 return llvm::DINodeArray();
1991 VarTemplateDecl *T = TS->getSpecializedTemplate();
1992 const TemplateParameterList *TList = T->getTemplateParameters();
1993 auto TA = TS->getTemplateArgs().asArray();
1994 return CollectTemplateParams(TList, TA, Unit);
1997 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1998 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1999 // Always get the full list of parameters, not just the ones from the
2000 // specialization. A partial specialization may have fewer parameters than
2001 // there are arguments.
2002 TemplateParameterList *TPList =
2003 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2004 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2005 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
2008 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2010 return VTablePtrType;
2012 ASTContext &Context = CGM.getContext();
2015 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2016 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2017 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2018 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2019 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2020 Optional<unsigned> DWARFAddressSpace =
2021 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2023 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2024 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2025 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2026 return VTablePtrType;
2029 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2030 // Copy the gdb compatible name on the side and use its reference.
2031 return internString("_vptr$", RD->getNameAsString());
2034 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2035 DynamicInitKind StubKind,
2036 llvm::Function *InitFn) {
2037 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2039 if (!CGM.getCodeGenOpts().EmitCodeView)
2040 return InitFn->getName();
2042 // Print the normal qualified name for the variable, then break off the last
2043 // NNS, and add the appropriate other text. Clang always prints the global
2044 // variable name without template arguments, so we can use rsplit("::") and
2045 // then recombine the pieces.
2046 SmallString<128> QualifiedGV;
2050 llvm::raw_svector_ostream OS(QualifiedGV);
2051 VD->printQualifiedName(OS, getPrintingPolicy());
2052 std::tie(Quals, GVName) = OS.str().rsplit("::");
2054 std::swap(Quals, GVName);
2057 SmallString<128> InitName;
2058 llvm::raw_svector_ostream OS(InitName);
2060 OS << Quals << "::";
2063 case DynamicInitKind::NoStub:
2064 llvm_unreachable("not an initializer");
2065 case DynamicInitKind::Initializer:
2066 OS << "`dynamic initializer for '";
2068 case DynamicInitKind::AtExit:
2069 OS << "`dynamic atexit destructor for '";
2075 // Add any template specialization args.
2076 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2077 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2078 getPrintingPolicy());
2083 return internString(OS.str());
2086 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2087 SmallVectorImpl<llvm::Metadata *> &EltTys,
2088 llvm::DICompositeType *RecordTy) {
2089 // If this class is not dynamic then there is not any vtable info to collect.
2090 if (!RD->isDynamicClass())
2093 // Don't emit any vtable shape or vptr info if this class doesn't have an
2094 // extendable vfptr. This can happen if the class doesn't have virtual
2095 // methods, or in the MS ABI if those virtual methods only come from virtually
2097 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2098 if (!RL.hasExtendableVFPtr())
2101 // CodeView needs to know how large the vtable of every dynamic class is, so
2102 // emit a special named pointer type into the element list. The vptr type
2103 // points to this type as well.
2104 llvm::DIType *VPtrTy = nullptr;
2105 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2106 CGM.getTarget().getCXXABI().isMicrosoft();
2107 if (NeedVTableShape) {
2109 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2110 const VTableLayout &VFTLayout =
2111 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2112 unsigned VSlotCount =
2113 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2114 unsigned VTableWidth = PtrWidth * VSlotCount;
2115 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2116 Optional<unsigned> DWARFAddressSpace =
2117 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2119 // Create a very wide void* type and insert it directly in the element list.
2120 llvm::DIType *VTableType = DBuilder.createPointerType(
2121 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2122 EltTys.push_back(VTableType);
2124 // The vptr is a pointer to this special vtable type.
2125 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2128 // If there is a primary base then the artificial vptr member lives there.
2129 if (RL.getPrimaryBase())
2133 VPtrTy = getOrCreateVTablePtrType(Unit);
2135 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2136 llvm::DIType *VPtrMember =
2137 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2138 llvm::DINode::FlagArtificial, VPtrTy);
2139 EltTys.push_back(VPtrMember);
2142 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2143 SourceLocation Loc) {
2144 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2145 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2149 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2150 SourceLocation Loc) {
2151 return getOrCreateStandaloneType(D, Loc);
2154 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2155 SourceLocation Loc) {
2156 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2157 assert(!D.isNull() && "null type");
2158 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2159 assert(T && "could not create debug info for type");
2161 RetainedTypes.push_back(D.getAsOpaquePtr());
2165 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2166 QualType AllocatedTy,
2167 SourceLocation Loc) {
2168 if (CGM.getCodeGenOpts().getDebugInfo() <=
2169 codegenoptions::DebugLineTablesOnly)
2172 if (AllocatedTy->isVoidType())
2173 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2175 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2177 CI->setMetadata("heapallocsite", node);
2180 void CGDebugInfo::completeType(const EnumDecl *ED) {
2181 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2183 QualType Ty = CGM.getContext().getEnumType(ED);
2184 void *TyPtr = Ty.getAsOpaquePtr();
2185 auto I = TypeCache.find(TyPtr);
2186 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2188 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2189 assert(!Res->isForwardDecl());
2190 TypeCache[TyPtr].reset(Res);
2193 void CGDebugInfo::completeType(const RecordDecl *RD) {
2194 if (DebugKind > codegenoptions::LimitedDebugInfo ||
2195 !CGM.getLangOpts().CPlusPlus)
2196 completeRequiredType(RD);
2199 /// Return true if the class or any of its methods are marked dllimport.
2200 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2201 if (RD->hasAttr<DLLImportAttr>())
2203 for (const CXXMethodDecl *MD : RD->methods())
2204 if (MD->hasAttr<DLLImportAttr>())
2209 /// Does a type definition exist in an imported clang module?
2210 static bool isDefinedInClangModule(const RecordDecl *RD) {
2211 // Only definitions that where imported from an AST file come from a module.
2212 if (!RD || !RD->isFromASTFile())
2214 // Anonymous entities cannot be addressed. Treat them as not from module.
2215 if (!RD->isExternallyVisible() && RD->getName().empty())
2217 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2218 if (!CXXDecl->isCompleteDefinition())
2220 // Check wether RD is a template.
2221 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2222 if (TemplateKind != TSK_Undeclared) {
2223 // Unfortunately getOwningModule() isn't accurate enough to find the
2224 // owning module of a ClassTemplateSpecializationDecl that is inside a
2225 // namespace spanning multiple modules.
2226 bool Explicit = false;
2227 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2228 Explicit = TD->isExplicitInstantiationOrSpecialization();
2229 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2231 // This is a template, check the origin of the first member.
2232 if (CXXDecl->field_begin() == CXXDecl->field_end())
2233 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2234 if (!CXXDecl->field_begin()->isFromASTFile())
2241 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2242 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2243 if (CXXRD->isDynamicClass() &&
2244 CGM.getVTableLinkage(CXXRD) ==
2245 llvm::GlobalValue::AvailableExternallyLinkage &&
2246 !isClassOrMethodDLLImport(CXXRD))
2249 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2255 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2256 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2258 QualType Ty = CGM.getContext().getRecordType(RD);
2259 void *TyPtr = Ty.getAsOpaquePtr();
2260 auto I = TypeCache.find(TyPtr);
2261 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2263 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2264 assert(!Res->isForwardDecl());
2265 TypeCache[TyPtr].reset(Res);
2268 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2269 CXXRecordDecl::method_iterator End) {
2270 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2271 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2272 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2273 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2278 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2279 bool DebugTypeExtRefs, const RecordDecl *RD,
2280 const LangOptions &LangOpts) {
2281 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2284 if (auto *ES = RD->getASTContext().getExternalSource())
2285 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2288 if (DebugKind > codegenoptions::LimitedDebugInfo)
2291 if (!LangOpts.CPlusPlus)
2294 if (!RD->isCompleteDefinitionRequired())
2297 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2302 // Only emit complete debug info for a dynamic class when its vtable is
2303 // emitted. However, Microsoft debuggers don't resolve type information
2304 // across DLL boundaries, so skip this optimization if the class or any of its
2305 // methods are marked dllimport. This isn't a complete solution, since objects
2306 // without any dllimport methods can be used in one DLL and constructed in
2307 // another, but it is the current behavior of LimitedDebugInfo.
2308 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2309 !isClassOrMethodDLLImport(CXXDecl))
2312 // In constructor debug mode, only emit debug info for a class when its
2313 // constructor is emitted. Skip this optimization if the class or any of
2314 // its methods are marked dllimport.
2315 if (DebugKind == codegenoptions::DebugInfoConstructor &&
2316 !CXXDecl->isLambda() && !CXXDecl->hasConstexprNonCopyMoveConstructor() &&
2317 !isClassOrMethodDLLImport(CXXDecl))
2318 for (const auto *Ctor : CXXDecl->ctors())
2319 if (Ctor->isUserProvided())
2322 TemplateSpecializationKind Spec = TSK_Undeclared;
2323 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2324 Spec = SD->getSpecializationKind();
2326 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2327 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2328 CXXDecl->method_end()))
2334 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2335 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2338 QualType Ty = CGM.getContext().getRecordType(RD);
2339 llvm::DIType *T = getTypeOrNull(Ty);
2340 if (T && T->isForwardDecl())
2341 completeClassData(RD);
2344 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2345 RecordDecl *RD = Ty->getDecl();
2346 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2347 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2348 CGM.getLangOpts())) {
2350 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2354 return CreateTypeDefinition(Ty);
2357 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2358 RecordDecl *RD = Ty->getDecl();
2360 // Get overall information about the record type for the debug info.
2361 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2363 // Records and classes and unions can all be recursive. To handle them, we
2364 // first generate a debug descriptor for the struct as a forward declaration.
2365 // Then (if it is a definition) we go through and get debug info for all of
2366 // its members. Finally, we create a descriptor for the complete type (which
2367 // may refer to the forward decl if the struct is recursive) and replace all
2368 // uses of the forward declaration with the final definition.
2369 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2371 const RecordDecl *D = RD->getDefinition();
2372 if (!D || !D->isCompleteDefinition())
2375 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2376 CollectContainingType(CXXDecl, FwdDecl);
2378 // Push the struct on region stack.
2379 LexicalBlockStack.emplace_back(&*FwdDecl);
2380 RegionMap[Ty->getDecl()].reset(FwdDecl);
2382 // Convert all the elements.
2383 SmallVector<llvm::Metadata *, 16> EltTys;
2384 // what about nested types?
2386 // Note: The split of CXXDecl information here is intentional, the
2387 // gdb tests will depend on a certain ordering at printout. The debug
2388 // information offsets are still correct if we merge them all together
2390 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2392 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2393 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2396 // Collect data fields (including static variables and any initializers).
2397 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2399 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2401 LexicalBlockStack.pop_back();
2402 RegionMap.erase(Ty->getDecl());
2404 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2405 DBuilder.replaceArrays(FwdDecl, Elements);
2407 if (FwdDecl->isTemporary())
2409 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2411 RegionMap[Ty->getDecl()].reset(FwdDecl);
2415 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2416 llvm::DIFile *Unit) {
2417 // Ignore protocols.
2418 return getOrCreateType(Ty->getBaseType(), Unit);
2421 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2422 llvm::DIFile *Unit) {
2423 // Ignore protocols.
2424 SourceLocation Loc = Ty->getDecl()->getLocation();
2426 // Use Typedefs to represent ObjCTypeParamType.
2427 return DBuilder.createTypedef(
2428 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2429 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2430 getDeclContextDescriptor(Ty->getDecl()));
2433 /// \return true if Getter has the default name for the property PD.
2434 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2435 const ObjCMethodDecl *Getter) {
2440 assert(Getter->getDeclName().isObjCZeroArgSelector());
2441 return PD->getName() ==
2442 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2445 /// \return true if Setter has the default name for the property PD.
2446 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2447 const ObjCMethodDecl *Setter) {
2452 assert(Setter->getDeclName().isObjCOneArgSelector());
2453 return SelectorTable::constructSetterName(PD->getName()) ==
2454 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2457 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2458 llvm::DIFile *Unit) {
2459 ObjCInterfaceDecl *ID = Ty->getDecl();
2463 // Return a forward declaration if this type was imported from a clang module,
2464 // and this is not the compile unit with the implementation of the type (which
2465 // may contain hidden ivars).
2466 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2467 !ID->getImplementation())
2468 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2470 getDeclContextDescriptor(ID), Unit, 0);
2472 // Get overall information about the record type for the debug info.
2473 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2474 unsigned Line = getLineNumber(ID->getLocation());
2476 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2478 // If this is just a forward declaration return a special forward-declaration
2479 // debug type since we won't be able to lay out the entire type.
2480 ObjCInterfaceDecl *Def = ID->getDefinition();
2481 if (!Def || !Def->getImplementation()) {
2482 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2483 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2484 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2485 DefUnit, Line, RuntimeLang);
2486 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2490 return CreateTypeDefinition(Ty, Unit);
2493 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2494 bool CreateSkeletonCU) {
2495 // Use the Module pointer as the key into the cache. This is a
2496 // nullptr if the "Module" is a PCH, which is safe because we don't
2497 // support chained PCH debug info, so there can only be a single PCH.
2498 const Module *M = Mod.getModuleOrNull();
2499 auto ModRef = ModuleCache.find(M);
2500 if (ModRef != ModuleCache.end())
2501 return cast<llvm::DIModule>(ModRef->second);
2503 // Macro definitions that were defined with "-D" on the command line.
2504 SmallString<128> ConfigMacros;
2506 llvm::raw_svector_ostream OS(ConfigMacros);
2507 const auto &PPOpts = CGM.getPreprocessorOpts();
2509 // Translate the macro definitions back into a command line.
2510 for (auto &M : PPOpts.Macros) {
2513 const std::string &Macro = M.first;
2514 bool Undef = M.second;
2515 OS << "\"-" << (Undef ? 'U' : 'D');
2516 for (char c : Macro)
2531 bool IsRootModule = M ? !M->Parent : true;
2532 // When a module name is specified as -fmodule-name, that module gets a
2533 // clang::Module object, but it won't actually be built or imported; it will
2535 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2536 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2537 "clang module without ASTFile must be specified by -fmodule-name");
2539 // Return a StringRef to the remapped Path.
2540 auto RemapPath = [this](StringRef Path) -> std::string {
2541 std::string Remapped = remapDIPath(Path);
2542 StringRef Relative(Remapped);
2543 StringRef CompDir = TheCU->getDirectory();
2544 if (Relative.consume_front(CompDir))
2545 Relative.consume_front(llvm::sys::path::get_separator());
2547 return Relative.str();
2550 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2551 // PCH files don't have a signature field in the control block,
2552 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2553 // We use the lower 64 bits for debug info.
2555 uint64_t Signature = 0;
2556 if (const auto &ModSig = Mod.getSignature()) {
2557 for (unsigned I = 0; I != sizeof(Signature); ++I)
2558 Signature |= (uint64_t)ModSig[I] << (I * 8);
2562 llvm::DIBuilder DIB(CGM.getModule());
2564 if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2565 PCM = Mod.getPath();
2566 llvm::sys::path::append(PCM, Mod.getASTFile());
2567 DIB.createCompileUnit(
2568 TheCU->getSourceLanguage(),
2569 // TODO: Support "Source" from external AST providers?
2570 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2571 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2572 llvm::DICompileUnit::FullDebug, Signature);
2576 llvm::DIModule *Parent =
2577 IsRootModule ? nullptr
2578 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2580 std::string IncludePath = Mod.getPath().str();
2581 llvm::DIModule *DIMod =
2582 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2583 RemapPath(IncludePath));
2584 ModuleCache[M].reset(DIMod);
2588 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2589 llvm::DIFile *Unit) {
2590 ObjCInterfaceDecl *ID = Ty->getDecl();
2591 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2592 unsigned Line = getLineNumber(ID->getLocation());
2593 unsigned RuntimeLang = TheCU->getSourceLanguage();
2595 // Bit size, align and offset of the type.
2596 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2597 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2599 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2600 if (ID->getImplementation())
2601 Flags |= llvm::DINode::FlagObjcClassComplete;
2603 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2604 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2605 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2606 nullptr, llvm::DINodeArray(), RuntimeLang);
2608 QualType QTy(Ty, 0);
2609 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2611 // Push the struct on region stack.
2612 LexicalBlockStack.emplace_back(RealDecl);
2613 RegionMap[Ty->getDecl()].reset(RealDecl);
2615 // Convert all the elements.
2616 SmallVector<llvm::Metadata *, 16> EltTys;
2618 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2620 llvm::DIType *SClassTy =
2621 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2625 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2626 llvm::DINode::FlagZero);
2627 EltTys.push_back(InhTag);
2630 // Create entries for all of the properties.
2631 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2632 SourceLocation Loc = PD->getLocation();
2633 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2634 unsigned PLine = getLineNumber(Loc);
2635 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2636 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2637 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2638 PD->getName(), PUnit, PLine,
2639 hasDefaultGetterName(PD, Getter) ? ""
2640 : getSelectorName(PD->getGetterName()),
2641 hasDefaultSetterName(PD, Setter) ? ""
2642 : getSelectorName(PD->getSetterName()),
2643 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2644 EltTys.push_back(PropertyNode);
2647 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2648 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2649 for (auto *PD : ClassExt->properties()) {
2650 PropertySet.insert(PD->getIdentifier());
2653 for (const auto *PD : ID->properties()) {
2654 // Don't emit duplicate metadata for properties that were already in a
2656 if (!PropertySet.insert(PD->getIdentifier()).second)
2662 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2663 unsigned FieldNo = 0;
2664 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2665 Field = Field->getNextIvar(), ++FieldNo) {
2666 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2670 StringRef FieldName = Field->getName();
2672 // Ignore unnamed fields.
2673 if (FieldName.empty())
2676 // Get the location for the field.
2677 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2678 unsigned FieldLine = getLineNumber(Field->getLocation());
2679 QualType FType = Field->getType();
2680 uint64_t FieldSize = 0;
2681 uint32_t FieldAlign = 0;
2683 if (!FType->isIncompleteArrayType()) {
2685 // Bit size, align and offset of the type.
2686 FieldSize = Field->isBitField()
2687 ? Field->getBitWidthValue(CGM.getContext())
2688 : CGM.getContext().getTypeSize(FType);
2689 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2692 uint64_t FieldOffset;
2693 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2694 // We don't know the runtime offset of an ivar if we're using the
2695 // non-fragile ABI. For bitfields, use the bit offset into the first
2696 // byte of storage of the bitfield. For other fields, use zero.
2697 if (Field->isBitField()) {
2699 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2700 FieldOffset %= CGM.getContext().getCharWidth();
2705 FieldOffset = RL.getFieldOffset(FieldNo);
2708 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2709 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2710 Flags = llvm::DINode::FlagProtected;
2711 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2712 Flags = llvm::DINode::FlagPrivate;
2713 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2714 Flags = llvm::DINode::FlagPublic;
2716 llvm::MDNode *PropertyNode = nullptr;
2717 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2718 if (ObjCPropertyImplDecl *PImpD =
2719 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2720 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2721 SourceLocation Loc = PD->getLocation();
2722 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2723 unsigned PLine = getLineNumber(Loc);
2724 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2725 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2726 PropertyNode = DBuilder.createObjCProperty(
2727 PD->getName(), PUnit, PLine,
2728 hasDefaultGetterName(PD, Getter)
2730 : getSelectorName(PD->getGetterName()),
2731 hasDefaultSetterName(PD, Setter)
2733 : getSelectorName(PD->getSetterName()),
2734 PD->getPropertyAttributes(),
2735 getOrCreateType(PD->getType(), PUnit));
2739 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2740 FieldSize, FieldAlign, FieldOffset, Flags,
2741 FieldTy, PropertyNode);
2742 EltTys.push_back(FieldTy);
2745 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2746 DBuilder.replaceArrays(RealDecl, Elements);
2748 LexicalBlockStack.pop_back();
2752 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2753 llvm::DIFile *Unit) {
2754 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2755 int64_t Count = Ty->getNumElements();
2757 llvm::Metadata *Subscript;
2758 QualType QTy(Ty, 0);
2759 auto SizeExpr = SizeExprCache.find(QTy);
2760 if (SizeExpr != SizeExprCache.end())
2761 Subscript = DBuilder.getOrCreateSubrange(
2762 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2763 nullptr /*upperBound*/, nullptr /*stride*/);
2766 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2767 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2768 Subscript = DBuilder.getOrCreateSubrange(
2769 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2770 nullptr /*stride*/);
2772 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2774 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2775 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2777 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2780 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
2781 llvm::DIFile *Unit) {
2782 // FIXME: Create another debug type for matrices
2783 // For the time being, it treats it like a nested ArrayType.
2785 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2786 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2787 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2789 // Create ranges for both dimensions.
2790 llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
2791 auto *ColumnCountNode =
2792 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2793 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
2794 auto *RowCountNode =
2795 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2796 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
2797 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2798 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2799 nullptr /*stride*/));
2800 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2801 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2802 nullptr /*stride*/));
2803 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2804 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
2807 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2811 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2812 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2814 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2816 } else if (Ty->isIncompleteArrayType()) {
2818 if (Ty->getElementType()->isIncompleteType())
2821 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2822 } else if (Ty->isIncompleteType()) {
2826 // Size and align of the whole array, not the element type.
2827 Size = CGM.getContext().getTypeSize(Ty);
2828 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2831 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2832 // interior arrays, do we care? Why aren't nested arrays represented the
2833 // obvious/recursive way?
2834 SmallVector<llvm::Metadata *, 8> Subscripts;
2835 QualType EltTy(Ty, 0);
2836 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2837 // If the number of elements is known, then count is that number. Otherwise,
2838 // it's -1. This allows us to represent a subrange with an array of 0
2839 // elements, like this:
2844 int64_t Count = -1; // Count == -1 is an unbounded array.
2845 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2846 Count = CAT->getSize().getZExtValue();
2847 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2848 if (Expr *Size = VAT->getSizeExpr()) {
2849 Expr::EvalResult Result;
2850 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2851 Count = Result.Val.getInt().getExtValue();
2855 auto SizeNode = SizeExprCache.find(EltTy);
2856 if (SizeNode != SizeExprCache.end())
2857 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2858 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
2859 nullptr /*upperBound*/, nullptr /*stride*/));
2862 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2863 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
2864 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2865 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2866 nullptr /*stride*/));
2868 EltTy = Ty->getElementType();
2871 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2873 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2877 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2878 llvm::DIFile *Unit) {
2879 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2880 Ty->getPointeeType(), Unit);
2883 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2884 llvm::DIFile *Unit) {
2885 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2886 Ty->getPointeeType(), Unit);
2889 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2891 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2894 if (!Ty->isIncompleteType()) {
2895 Size = CGM.getContext().getTypeSize(Ty);
2897 // Set the MS inheritance model. There is no flag for the unspecified model.
2898 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2899 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2900 case MSInheritanceModel::Single:
2901 Flags |= llvm::DINode::FlagSingleInheritance;
2903 case MSInheritanceModel::Multiple:
2904 Flags |= llvm::DINode::FlagMultipleInheritance;
2906 case MSInheritanceModel::Virtual:
2907 Flags |= llvm::DINode::FlagVirtualInheritance;
2909 case MSInheritanceModel::Unspecified:
2915 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2916 if (Ty->isMemberDataPointerType())
2917 return DBuilder.createMemberPointerType(
2918 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2921 const FunctionProtoType *FPT =
2922 Ty->getPointeeType()->getAs<FunctionProtoType>();
2923 return DBuilder.createMemberPointerType(
2924 getOrCreateInstanceMethodType(
2925 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2927 ClassType, Size, /*Align=*/0, Flags);
2930 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2931 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2932 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2935 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2936 return getOrCreateType(Ty->getElementType(), U);
2939 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2940 const EnumDecl *ED = Ty->getDecl();
2944 if (!ED->getTypeForDecl()->isIncompleteType()) {
2945 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2946 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2949 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2951 bool isImportedFromModule =
2952 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2954 // If this is just a forward declaration, construct an appropriately
2955 // marked node and just return it.
2956 if (isImportedFromModule || !ED->getDefinition()) {
2957 // Note that it is possible for enums to be created as part of
2958 // their own declcontext. In this case a FwdDecl will be created
2959 // twice. This doesn't cause a problem because both FwdDecls are
2960 // entered into the ReplaceMap: finalize() will replace the first
2961 // FwdDecl with the second and then replace the second with
2963 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2964 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2965 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2966 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2968 unsigned Line = getLineNumber(ED->getLocation());
2969 StringRef EDName = ED->getName();
2970 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2971 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2972 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2974 ReplaceMap.emplace_back(
2975 std::piecewise_construct, std::make_tuple(Ty),
2976 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2980 return CreateTypeDefinition(Ty);
2983 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2984 const EnumDecl *ED = Ty->getDecl();
2987 if (!ED->getTypeForDecl()->isIncompleteType()) {
2988 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2989 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2992 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2994 // Create elements for each enumerator.
2995 SmallVector<llvm::Metadata *, 16> Enumerators;
2996 ED = ED->getDefinition();
2997 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2998 for (const auto *Enum : ED->enumerators()) {
2999 const auto &InitVal = Enum->getInitVal();
3000 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
3001 Enumerators.push_back(
3002 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
3005 // Return a CompositeType for the enum itself.
3006 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3008 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3009 unsigned Line = getLineNumber(ED->getLocation());
3010 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3011 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3012 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3013 Line, Size, Align, EltArray, ClassTy,
3014 Identifier, ED->isScoped());
3017 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3018 unsigned MType, SourceLocation LineLoc,
3019 StringRef Name, StringRef Value) {
3020 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3021 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3024 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3025 SourceLocation LineLoc,
3026 SourceLocation FileLoc) {
3027 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3028 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3029 return DBuilder.createTempMacroFile(Parent, Line, FName);
3032 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3035 Qualifiers InnerQuals = T.getLocalQualifiers();
3036 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3037 // that is already there.
3038 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3039 Quals += InnerQuals;
3041 switch (T->getTypeClass()) {
3043 return C.getQualifiedType(T.getTypePtr(), Quals);
3044 case Type::TemplateSpecialization: {
3045 const auto *Spec = cast<TemplateSpecializationType>(T);
3046 if (Spec->isTypeAlias())
3047 return C.getQualifiedType(T.getTypePtr(), Quals);
3048 T = Spec->desugar();
3051 case Type::TypeOfExpr:
3052 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3055 T = cast<TypeOfType>(T)->getUnderlyingType();
3057 case Type::Decltype:
3058 T = cast<DecltypeType>(T)->getUnderlyingType();
3060 case Type::UnaryTransform:
3061 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3063 case Type::Attributed:
3064 T = cast<AttributedType>(T)->getEquivalentType();
3066 case Type::Elaborated:
3067 T = cast<ElaboratedType>(T)->getNamedType();
3070 T = cast<ParenType>(T)->getInnerType();
3072 case Type::MacroQualified:
3073 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3075 case Type::SubstTemplateTypeParm:
3076 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3079 case Type::DeducedTemplateSpecialization: {
3080 QualType DT = cast<DeducedType>(T)->getDeducedType();
3081 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3085 case Type::Adjusted:
3087 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3088 T = cast<AdjustedType>(T)->getAdjustedType();
3092 assert(T != LastT && "Type unwrapping failed to unwrap!");
3097 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3099 // Unwrap the type as needed for debug information.
3100 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3102 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3103 if (It != TypeCache.end()) {
3104 // Verify that the debug info still exists.
3105 if (llvm::Metadata *V = It->second)
3106 return cast<llvm::DIType>(V);
3112 void CGDebugInfo::completeTemplateDefinition(
3113 const ClassTemplateSpecializationDecl &SD) {
3114 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3116 completeUnusedClass(SD);
3119 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3120 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3123 completeClassData(&D);
3124 // In case this type has no member function definitions being emitted, ensure
3126 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3129 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3133 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3135 llvm::raw_string_ostream OS(Name);
3136 Ty.print(OS, getPrintingPolicy());
3140 // Unwrap the type as needed for debug information.
3141 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3143 if (auto *T = getTypeOrNull(Ty))
3146 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3147 void *TyPtr = Ty.getAsOpaquePtr();
3149 // And update the type cache.
3150 TypeCache[TyPtr].reset(Res);
3155 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3156 // A forward declaration inside a module header does not belong to the module.
3157 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3159 if (DebugTypeExtRefs && D->isFromASTFile()) {
3160 // Record a reference to an imported clang module or precompiled header.
3161 auto *Reader = CGM.getContext().getExternalSource();
3162 auto Idx = D->getOwningModuleID();
3163 auto Info = Reader->getSourceDescriptor(Idx);
3165 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3166 } else if (ClangModuleMap) {
3167 // We are building a clang module or a precompiled header.
3169 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3170 // and it wouldn't be necessary to specify the parent scope
3171 // because the type is already unique by definition (it would look
3172 // like the output of -fno-standalone-debug). On the other hand,
3173 // the parent scope helps a consumer to quickly locate the object
3174 // file where the type's definition is located, so it might be
3175 // best to make this behavior a command line or debugger tuning
3177 if (Module *M = D->getOwningModule()) {
3178 // This is a (sub-)module.
3179 auto Info = ASTSourceDescriptor(*M);
3180 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3182 // This the precompiled header being built.
3183 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3190 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3191 // Handle qualifiers, which recursively handles what they refer to.
3192 if (Ty.hasLocalQualifiers())
3193 return CreateQualifiedType(Ty, Unit);
3195 // Work out details of type.
3196 switch (Ty->getTypeClass()) {
3197 #define TYPE(Class, Base)
3198 #define ABSTRACT_TYPE(Class, Base)
3199 #define NON_CANONICAL_TYPE(Class, Base)
3200 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3201 #include "clang/AST/TypeNodes.inc"
3202 llvm_unreachable("Dependent types cannot show up in debug information");
3204 case Type::ExtVector:
3206 return CreateType(cast<VectorType>(Ty), Unit);
3207 case Type::ConstantMatrix:
3208 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3209 case Type::ObjCObjectPointer:
3210 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3211 case Type::ObjCObject:
3212 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3213 case Type::ObjCTypeParam:
3214 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3215 case Type::ObjCInterface:
3216 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3218 return CreateType(cast<BuiltinType>(Ty));
3220 return CreateType(cast<ComplexType>(Ty));
3222 return CreateType(cast<PointerType>(Ty), Unit);
3223 case Type::BlockPointer:
3224 return CreateType(cast<BlockPointerType>(Ty), Unit);
3226 return CreateType(cast<TypedefType>(Ty), Unit);
3228 return CreateType(cast<RecordType>(Ty));
3230 return CreateEnumType(cast<EnumType>(Ty));
3231 case Type::FunctionProto:
3232 case Type::FunctionNoProto:
3233 return CreateType(cast<FunctionType>(Ty), Unit);
3234 case Type::ConstantArray:
3235 case Type::VariableArray:
3236 case Type::IncompleteArray:
3237 return CreateType(cast<ArrayType>(Ty), Unit);
3239 case Type::LValueReference:
3240 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3241 case Type::RValueReference:
3242 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3244 case Type::MemberPointer:
3245 return CreateType(cast<MemberPointerType>(Ty), Unit);
3248 return CreateType(cast<AtomicType>(Ty), Unit);
3251 return CreateType(cast<ExtIntType>(Ty));
3253 return CreateType(cast<PipeType>(Ty), Unit);
3255 case Type::TemplateSpecialization:
3256 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3259 case Type::Attributed:
3260 case Type::Adjusted:
3262 case Type::DeducedTemplateSpecialization:
3263 case Type::Elaborated:
3265 case Type::MacroQualified:
3266 case Type::SubstTemplateTypeParm:
3267 case Type::TypeOfExpr:
3269 case Type::Decltype:
3270 case Type::UnaryTransform:
3271 case Type::PackExpansion:
3275 llvm_unreachable("type should have been unwrapped!");
3278 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3279 llvm::DIFile *Unit) {
3280 QualType QTy(Ty, 0);
3282 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3284 // We may have cached a forward decl when we could have created
3285 // a non-forward decl. Go ahead and create a non-forward decl
3287 if (T && !T->isForwardDecl())
3290 // Otherwise create the type.
3291 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3293 // Propagate members from the declaration to the definition
3294 // CreateType(const RecordType*) will overwrite this with the members in the
3295 // correct order if the full type is needed.
3296 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3298 // And update the type cache.
3299 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3303 // TODO: Currently used for context chains when limiting debug info.
3304 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3305 RecordDecl *RD = Ty->getDecl();
3307 // Get overall information about the record type for the debug info.
3308 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3309 unsigned Line = getLineNumber(RD->getLocation());
3310 StringRef RDName = getClassName(RD);
3312 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3314 // If we ended up creating the type during the context chain construction,
3315 // just return that.
3316 auto *T = cast_or_null<llvm::DICompositeType>(
3317 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3318 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3321 // If this is just a forward or incomplete declaration, construct an
3322 // appropriately marked node and just return it.
3323 const RecordDecl *D = RD->getDefinition();
3324 if (!D || !D->isCompleteDefinition())
3325 return getOrCreateRecordFwdDecl(Ty, RDContext);
3327 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3328 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3330 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3332 // Explicitly record the calling convention and export symbols for C++
3334 auto Flags = llvm::DINode::FlagZero;
3335 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3336 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3337 Flags |= llvm::DINode::FlagTypePassByReference;
3339 Flags |= llvm::DINode::FlagTypePassByValue;
3341 // Record if a C++ record is non-trivial type.
3342 if (!CXXRD->isTrivial())
3343 Flags |= llvm::DINode::FlagNonTrivial;
3345 // Record exports it symbols to the containing structure.
3346 if (CXXRD->isAnonymousStructOrUnion())
3347 Flags |= llvm::DINode::FlagExportSymbols;
3350 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3351 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3354 // Elements of composite types usually have back to the type, creating
3355 // uniquing cycles. Distinct nodes are more efficient.
3356 switch (RealDecl->getTag()) {
3358 llvm_unreachable("invalid composite type tag");
3360 case llvm::dwarf::DW_TAG_array_type:
3361 case llvm::dwarf::DW_TAG_enumeration_type:
3362 // Array elements and most enumeration elements don't have back references,
3363 // so they don't tend to be involved in uniquing cycles and there is some
3364 // chance of merging them when linking together two modules. Only make
3365 // them distinct if they are ODR-uniqued.
3366 if (Identifier.empty())
3370 case llvm::dwarf::DW_TAG_structure_type:
3371 case llvm::dwarf::DW_TAG_union_type:
3372 case llvm::dwarf::DW_TAG_class_type:
3373 // Immediately resolve to a distinct node.
3375 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3379 RegionMap[Ty->getDecl()].reset(RealDecl);
3380 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3382 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3383 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3384 CollectCXXTemplateParams(TSpecial, DefUnit));
3388 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3389 llvm::DICompositeType *RealDecl) {
3390 // A class's primary base or the class itself contains the vtable.
3391 llvm::DICompositeType *ContainingType = nullptr;
3392 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3393 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3394 // Seek non-virtual primary base root.
3396 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3397 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3398 if (PBT && !BRL.isPrimaryBaseVirtual())
3403 ContainingType = cast<llvm::DICompositeType>(
3404 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3405 getOrCreateFile(RD->getLocation())));
3406 } else if (RD->isDynamicClass())
3407 ContainingType = RealDecl;
3409 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3412 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3413 StringRef Name, uint64_t *Offset) {
3414 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3415 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3416 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3418 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3419 *Offset, llvm::DINode::FlagZero, FieldTy);
3420 *Offset += FieldSize;
3424 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3426 StringRef &LinkageName,
3427 llvm::DIScope *&FDContext,
3428 llvm::DINodeArray &TParamsArray,
3429 llvm::DINode::DIFlags &Flags) {
3430 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3431 Name = getFunctionName(FD);
3432 // Use mangled name as linkage name for C/C++ functions.
3433 if (FD->hasPrototype()) {
3434 LinkageName = CGM.getMangledName(GD);
3435 Flags |= llvm::DINode::FlagPrototyped;
3437 // No need to replicate the linkage name if it isn't different from the
3438 // subprogram name, no need to have it at all unless coverage is enabled or
3439 // debug is set to more than just line tables or extra debug info is needed.
3440 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3441 !CGM.getCodeGenOpts().EmitGcovNotes &&
3442 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3443 DebugKind <= codegenoptions::DebugLineTablesOnly))
3444 LinkageName = StringRef();
3446 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3447 if (const NamespaceDecl *NSDecl =
3448 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3449 FDContext = getOrCreateNamespace(NSDecl);
3450 else if (const RecordDecl *RDecl =
3451 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3452 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3453 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3455 // Check if it is a noreturn-marked function
3456 if (FD->isNoReturn())
3457 Flags |= llvm::DINode::FlagNoReturn;
3458 // Collect template parameters.
3459 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3463 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3464 unsigned &LineNo, QualType &T,
3465 StringRef &Name, StringRef &LinkageName,
3466 llvm::MDTuple *&TemplateParameters,
3467 llvm::DIScope *&VDContext) {
3468 Unit = getOrCreateFile(VD->getLocation());
3469 LineNo = getLineNumber(VD->getLocation());
3471 setLocation(VD->getLocation());
3474 if (T->isIncompleteArrayType()) {
3475 // CodeGen turns int[] into int[1] so we'll do the same here.
3476 llvm::APInt ConstVal(32, 1);
3477 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3479 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3480 ArrayType::Normal, 0);
3483 Name = VD->getName();
3484 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3485 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3486 LinkageName = CGM.getMangledName(VD);
3487 if (LinkageName == Name)
3488 LinkageName = StringRef();
3490 if (isa<VarTemplateSpecializationDecl>(VD)) {
3491 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3492 TemplateParameters = parameterNodes.get();
3494 TemplateParameters = nullptr;
3497 // Since we emit declarations (DW_AT_members) for static members, place the
3498 // definition of those static members in the namespace they were declared in
3499 // in the source code (the lexical decl context).
3500 // FIXME: Generalize this for even non-member global variables where the
3501 // declaration and definition may have different lexical decl contexts, once
3502 // we have support for emitting declarations of (non-member) global variables.
3503 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3504 : VD->getDeclContext();
3505 // When a record type contains an in-line initialization of a static data
3506 // member, and the record type is marked as __declspec(dllexport), an implicit
3507 // definition of the member will be created in the record context. DWARF
3508 // doesn't seem to have a nice way to describe this in a form that consumers
3509 // are likely to understand, so fake the "normal" situation of a definition
3510 // outside the class by putting it in the global scope.
3512 DC = CGM.getContext().getTranslationUnitDecl();
3514 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3515 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3518 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3520 llvm::DINodeArray TParamsArray;
3521 StringRef Name, LinkageName;
3522 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3523 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3524 SourceLocation Loc = GD.getDecl()->getLocation();
3525 llvm::DIFile *Unit = getOrCreateFile(Loc);
3526 llvm::DIScope *DContext = Unit;
3527 unsigned Line = getLineNumber(Loc);
3528 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3530 auto *FD = cast<FunctionDecl>(GD.getDecl());
3532 // Build function type.
3533 SmallVector<QualType, 16> ArgTypes;
3534 for (const ParmVarDecl *Parm : FD->parameters())
3535 ArgTypes.push_back(Parm->getType());
3537 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3538 QualType FnType = CGM.getContext().getFunctionType(
3539 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3540 if (!FD->isExternallyVisible())
3541 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3542 if (CGM.getLangOpts().Optimize)
3543 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3546 Flags |= getCallSiteRelatedAttrs();
3547 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3548 return DBuilder.createFunction(
3549 DContext, Name, LinkageName, Unit, Line,
3550 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3551 TParamsArray.get(), getFunctionDeclaration(FD));
3554 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3555 DContext, Name, LinkageName, Unit, Line,
3556 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3557 TParamsArray.get(), getFunctionDeclaration(FD));
3558 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3559 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3560 std::make_tuple(CanonDecl),
3561 std::make_tuple(SP));
3565 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3566 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3569 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3570 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3573 llvm::DIGlobalVariable *
3574 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3576 StringRef Name, LinkageName;
3577 SourceLocation Loc = VD->getLocation();
3578 llvm::DIFile *Unit = getOrCreateFile(Loc);
3579 llvm::DIScope *DContext = Unit;
3580 unsigned Line = getLineNumber(Loc);
3581 llvm::MDTuple *TemplateParameters = nullptr;
3583 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3585 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3586 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3587 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3588 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3589 FwdDeclReplaceMap.emplace_back(
3590 std::piecewise_construct,
3591 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3592 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3596 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3597 // We only need a declaration (not a definition) of the type - so use whatever
3598 // we would otherwise do to get a type for a pointee. (forward declarations in
3599 // limited debug info, full definitions (if the type definition is available)
3600 // in unlimited debug info)
3601 if (const auto *TD = dyn_cast<TypeDecl>(D))
3602 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3603 getOrCreateFile(TD->getLocation()));
3604 auto I = DeclCache.find(D->getCanonicalDecl());
3606 if (I != DeclCache.end()) {
3608 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3609 return GVE->getVariable();
3610 return dyn_cast_or_null<llvm::DINode>(N);
3613 // No definition for now. Emit a forward definition that might be
3614 // merged with a potential upcoming definition.
3615 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3616 return getFunctionForwardDeclaration(FD);
3617 else if (const auto *VD = dyn_cast<VarDecl>(D))
3618 return getGlobalVariableForwardDeclaration(VD);
3623 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3624 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3627 const auto *FD = dyn_cast<FunctionDecl>(D);
3632 auto *S = getDeclContextDescriptor(D);
3634 auto MI = SPCache.find(FD->getCanonicalDecl());
3635 if (MI == SPCache.end()) {
3636 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3637 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3638 cast<llvm::DICompositeType>(S));
3641 if (MI != SPCache.end()) {
3642 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3643 if (SP && !SP->isDefinition())
3647 for (auto NextFD : FD->redecls()) {
3648 auto MI = SPCache.find(NextFD->getCanonicalDecl());
3649 if (MI != SPCache.end()) {
3650 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3651 if (SP && !SP->isDefinition())
3658 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3659 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3660 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3661 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3664 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3668 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3671 if (OMD->isDirectMethod())
3672 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3674 // Starting with DWARF V5 method declarations are emitted as children of
3675 // the interface type.
3676 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3678 ID = OMD->getClassInterface();
3681 QualType QTy(ID->getTypeForDecl(), 0);
3682 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3683 if (It == TypeCache.end())
3685 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3686 llvm::DISubprogram *FD = DBuilder.createFunction(
3687 InterfaceType, getObjCMethodName(OMD), StringRef(),
3688 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3689 DBuilder.finalizeSubprogram(FD);
3690 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3694 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3695 // implicit parameter "this".
3696 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3699 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3700 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3701 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3702 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3704 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3705 return getOrCreateMethodType(Method, F, false);
3707 const auto *FTy = FnType->getAs<FunctionType>();
3708 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3710 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3711 // Add "self" and "_cmd"
3712 SmallVector<llvm::Metadata *, 16> Elts;
3714 // First element is always return type. For 'void' functions it is NULL.
3715 QualType ResultTy = OMethod->getReturnType();
3717 // Replace the instancetype keyword with the actual type.
3718 if (ResultTy == CGM.getContext().getObjCInstanceType())
3719 ResultTy = CGM.getContext().getPointerType(
3720 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3722 Elts.push_back(getOrCreateType(ResultTy, F));
3723 // "self" pointer is always first argument.
3724 QualType SelfDeclTy;
3725 if (auto *SelfDecl = OMethod->getSelfDecl())
3726 SelfDeclTy = SelfDecl->getType();
3727 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3728 if (FPT->getNumParams() > 1)
3729 SelfDeclTy = FPT->getParamType(0);
3730 if (!SelfDeclTy.isNull())
3732 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3733 // "_cmd" pointer is always second argument.
3734 Elts.push_back(DBuilder.createArtificialType(
3735 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3736 // Get rest of the arguments.
3737 for (const auto *PI : OMethod->parameters())
3738 Elts.push_back(getOrCreateType(PI->getType(), F));
3739 // Variadic methods need a special marker at the end of the type list.
3740 if (OMethod->isVariadic())
3741 Elts.push_back(DBuilder.createUnspecifiedParameter());
3743 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3744 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3748 // Handle variadic function types; they need an additional
3749 // unspecified parameter.
3750 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3751 if (FD->isVariadic()) {
3752 SmallVector<llvm::Metadata *, 16> EltTys;
3753 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3754 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3755 for (QualType ParamType : FPT->param_types())
3756 EltTys.push_back(getOrCreateType(ParamType, F));
3757 EltTys.push_back(DBuilder.createUnspecifiedParameter());
3758 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3759 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3763 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3766 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3767 SourceLocation ScopeLoc, QualType FnType,
3768 llvm::Function *Fn, bool CurFuncIsThunk,
3769 CGBuilderTy &Builder) {
3772 StringRef LinkageName;
3774 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3776 const Decl *D = GD.getDecl();
3777 bool HasDecl = (D != nullptr);
3779 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3780 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3781 llvm::DIFile *Unit = getOrCreateFile(Loc);
3782 llvm::DIScope *FDContext = Unit;
3783 llvm::DINodeArray TParamsArray;
3785 // Use llvm function name.
3786 LinkageName = Fn->getName();
3787 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3788 // If there is a subprogram for this function available then use it.
3789 auto FI = SPCache.find(FD->getCanonicalDecl());
3790 if (FI != SPCache.end()) {
3791 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3792 if (SP && SP->isDefinition()) {
3793 LexicalBlockStack.emplace_back(SP);
3794 RegionMap[D].reset(SP);
3798 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3799 TParamsArray, Flags);
3800 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3801 Name = getObjCMethodName(OMD);
3802 Flags |= llvm::DINode::FlagPrototyped;
3803 } else if (isa<VarDecl>(D) &&
3804 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3805 // This is a global initializer or atexit destructor for a global variable.
3806 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3809 Name = Fn->getName();
3811 if (isa<BlockDecl>(D))
3814 Flags |= llvm::DINode::FlagPrototyped;
3816 if (Name.startswith("\01"))
3817 Name = Name.substr(1);
3819 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3820 Flags |= llvm::DINode::FlagArtificial;
3821 // Artificial functions should not silently reuse CurLoc.
3822 CurLoc = SourceLocation();
3826 Flags |= llvm::DINode::FlagThunk;
3828 if (Fn->hasLocalLinkage())
3829 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3830 if (CGM.getLangOpts().Optimize)
3831 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3833 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3834 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3835 SPFlags | llvm::DISubprogram::SPFlagDefinition;
3837 unsigned LineNo = getLineNumber(Loc);
3838 unsigned ScopeLine = getLineNumber(ScopeLoc);
3839 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3840 llvm::DISubprogram *Decl = nullptr;
3842 Decl = isa<ObjCMethodDecl>(D)
3843 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3844 : getFunctionDeclaration(D);
3846 // FIXME: The function declaration we're constructing here is mostly reusing
3847 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3848 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3849 // all subprograms instead of the actual context since subprogram definitions
3850 // are emitted as CU level entities by the backend.
3851 llvm::DISubprogram *SP = DBuilder.createFunction(
3852 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3853 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3854 Fn->setSubprogram(SP);
3855 // We might get here with a VarDecl in the case we're generating
3856 // code for the initialization of globals. Do not record these decls
3857 // as they will overwrite the actual VarDecl Decl in the cache.
3858 if (HasDecl && isa<FunctionDecl>(D))
3859 DeclCache[D->getCanonicalDecl()].reset(SP);
3861 // Push the function onto the lexical block stack.
3862 LexicalBlockStack.emplace_back(SP);
3865 RegionMap[D].reset(SP);
3868 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3869 QualType FnType, llvm::Function *Fn) {
3871 StringRef LinkageName;
3873 const Decl *D = GD.getDecl();
3877 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3879 llvm::raw_string_ostream OS(Name);
3880 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3881 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3882 /*Qualified=*/true);
3886 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3887 llvm::DIFile *Unit = getOrCreateFile(Loc);
3888 bool IsDeclForCallSite = Fn ? true : false;
3889 llvm::DIScope *FDContext =
3890 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3891 llvm::DINodeArray TParamsArray;
3892 if (isa<FunctionDecl>(D)) {
3893 // If there is a DISubprogram for this function available then use it.
3894 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3895 TParamsArray, Flags);
3896 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3897 Name = getObjCMethodName(OMD);
3898 Flags |= llvm::DINode::FlagPrototyped;
3900 llvm_unreachable("not a function or ObjC method");
3902 if (!Name.empty() && Name[0] == '\01')
3903 Name = Name.substr(1);
3905 if (D->isImplicit()) {
3906 Flags |= llvm::DINode::FlagArtificial;
3907 // Artificial functions without a location should not silently reuse CurLoc.
3908 if (Loc.isInvalid())
3909 CurLoc = SourceLocation();
3911 unsigned LineNo = getLineNumber(Loc);
3912 unsigned ScopeLine = 0;
3913 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3914 if (CGM.getLangOpts().Optimize)
3915 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3917 llvm::DISubprogram *SP = DBuilder.createFunction(
3918 FDContext, Name, LinkageName, Unit, LineNo,
3919 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3920 TParamsArray.get(), getFunctionDeclaration(D));
3922 if (IsDeclForCallSite)
3923 Fn->setSubprogram(SP);
3925 DBuilder.finalizeSubprogram(SP);
3928 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3929 QualType CalleeType,
3930 const FunctionDecl *CalleeDecl) {
3933 auto *Func = CallOrInvoke->getCalledFunction();
3936 if (Func->getSubprogram())
3939 // Do not emit a declaration subprogram for a builtin, a function with nodebug
3940 // attribute, or if call site info isn't required. Also, elide declarations
3941 // for functions with reserved names, as call site-related features aren't
3942 // interesting in this case (& also, the compiler may emit calls to these
3943 // functions without debug locations, which makes the verifier complain).
3944 if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
3945 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3947 if (const auto *Id = CalleeDecl->getIdentifier())
3948 if (Id->isReservedName())
3951 // If there is no DISubprogram attached to the function being called,
3952 // create the one describing the function in order to have complete
3953 // call site debug info.
3954 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3955 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
3958 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3959 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3960 // If there is a subprogram for this function available then use it.
3961 auto FI = SPCache.find(FD->getCanonicalDecl());
3962 llvm::DISubprogram *SP = nullptr;
3963 if (FI != SPCache.end())
3964 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3965 if (!SP || !SP->isDefinition())
3966 SP = getFunctionStub(GD);
3967 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3968 LexicalBlockStack.emplace_back(SP);
3969 setInlinedAt(Builder.getCurrentDebugLocation());
3970 EmitLocation(Builder, FD->getLocation());
3973 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3974 assert(CurInlinedAt && "unbalanced inline scope stack");
3975 EmitFunctionEnd(Builder, nullptr);
3976 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3979 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3980 // Update our current location
3983 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
3986 llvm::MDNode *Scope = LexicalBlockStack.back();
3987 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3988 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3991 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3992 llvm::MDNode *Back = nullptr;
3993 if (!LexicalBlockStack.empty())
3994 Back = LexicalBlockStack.back().get();
3995 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3996 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3997 getColumnNumber(CurLoc)));
4000 void CGDebugInfo::AppendAddressSpaceXDeref(
4001 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
4002 Optional<unsigned> DWARFAddressSpace =
4003 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4004 if (!DWARFAddressSpace)
4007 Expr.push_back(llvm::dwarf::DW_OP_constu);
4008 Expr.push_back(DWARFAddressSpace.getValue());
4009 Expr.push_back(llvm::dwarf::DW_OP_swap);
4010 Expr.push_back(llvm::dwarf::DW_OP_xderef);
4013 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4014 SourceLocation Loc) {
4015 // Set our current location.
4018 // Emit a line table change for the current location inside the new scope.
4019 Builder.SetCurrentDebugLocation(
4020 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
4021 LexicalBlockStack.back(), CurInlinedAt));
4023 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4026 // Create a new lexical block and push it on the stack.
4027 CreateLexicalBlock(Loc);
4030 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4031 SourceLocation Loc) {
4032 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4034 // Provide an entry in the line table for the end of the block.
4035 EmitLocation(Builder, Loc);
4037 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4040 LexicalBlockStack.pop_back();
4043 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4044 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4045 unsigned RCount = FnBeginRegionCount.back();
4046 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4048 // Pop all regions for this function.
4049 while (LexicalBlockStack.size() != RCount) {
4050 // Provide an entry in the line table for the end of the block.
4051 EmitLocation(Builder, CurLoc);
4052 LexicalBlockStack.pop_back();
4054 FnBeginRegionCount.pop_back();
4056 if (Fn && Fn->getSubprogram())
4057 DBuilder.finalizeSubprogram(Fn->getSubprogram());
4060 CGDebugInfo::BlockByRefType
4061 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4062 uint64_t *XOffset) {
4063 SmallVector<llvm::Metadata *, 5> EltTys;
4065 uint64_t FieldSize, FieldOffset;
4066 uint32_t FieldAlign;
4068 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4069 QualType Type = VD->getType();
4072 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4073 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4074 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4075 FType = CGM.getContext().IntTy;
4076 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4077 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4079 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4080 if (HasCopyAndDispose) {
4081 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4083 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4085 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4087 bool HasByrefExtendedLayout;
4088 Qualifiers::ObjCLifetime Lifetime;
4089 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4090 HasByrefExtendedLayout) &&
4091 HasByrefExtendedLayout) {
4092 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4094 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4097 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4098 if (Align > CGM.getContext().toCharUnitsFromBits(
4099 CGM.getTarget().getPointerAlign(0))) {
4100 CharUnits FieldOffsetInBytes =
4101 CGM.getContext().toCharUnitsFromBits(FieldOffset);
4102 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4103 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4105 if (NumPaddingBytes.isPositive()) {
4106 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4107 FType = CGM.getContext().getConstantArrayType(
4108 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4109 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4114 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4115 FieldSize = CGM.getContext().getTypeSize(FType);
4116 FieldAlign = CGM.getContext().toBits(Align);
4118 *XOffset = FieldOffset;
4119 llvm::DIType *FieldTy = DBuilder.createMemberType(
4120 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4121 llvm::DINode::FlagZero, WrappedTy);
4122 EltTys.push_back(FieldTy);
4123 FieldOffset += FieldSize;
4125 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4126 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4127 llvm::DINode::FlagZero, nullptr, Elements),
4131 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4132 llvm::Value *Storage,
4133 llvm::Optional<unsigned> ArgNo,
4134 CGBuilderTy &Builder,
4135 const bool UsePointerValue) {
4136 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4137 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4138 if (VD->hasAttr<NoDebugAttr>())
4142 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4143 cast<Decl>(VD->getDeclContext())->isImplicit());
4144 llvm::DIFile *Unit = nullptr;
4146 Unit = getOrCreateFile(VD->getLocation());
4148 uint64_t XOffset = 0;
4149 if (VD->hasAttr<BlocksAttr>())
4150 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4152 Ty = getOrCreateType(VD->getType(), Unit);
4154 // If there is no debug info for this type then do not emit debug info
4155 // for this variable.
4159 // Get location information.
4161 unsigned Column = 0;
4163 Line = getLineNumber(VD->getLocation());
4164 Column = getColumnNumber(VD->getLocation());
4166 SmallVector<int64_t, 13> Expr;
4167 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4168 if (VD->isImplicit())
4169 Flags |= llvm::DINode::FlagArtificial;
4171 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4173 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4174 AppendAddressSpaceXDeref(AddressSpace, Expr);
4176 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4177 // object pointer flag.
4178 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4179 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4180 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4181 Flags |= llvm::DINode::FlagObjectPointer;
4184 // Note: Older versions of clang used to emit byval references with an extra
4185 // DW_OP_deref, because they referenced the IR arg directly instead of
4186 // referencing an alloca. Newer versions of LLVM don't treat allocas
4187 // differently from other function arguments when used in a dbg.declare.
4188 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4189 StringRef Name = VD->getName();
4190 if (!Name.empty()) {
4191 if (VD->hasAttr<BlocksAttr>()) {
4192 // Here, we need an offset *into* the alloca.
4193 CharUnits offset = CharUnits::fromQuantity(32);
4194 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4195 // offset of __forwarding field
4196 offset = CGM.getContext().toCharUnitsFromBits(
4197 CGM.getTarget().getPointerWidth(0));
4198 Expr.push_back(offset.getQuantity());
4199 Expr.push_back(llvm::dwarf::DW_OP_deref);
4200 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4201 // offset of x field
4202 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4203 Expr.push_back(offset.getQuantity());
4205 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4206 // If VD is an anonymous union then Storage represents value for
4207 // all union fields.
4208 const RecordDecl *RD = RT->getDecl();
4209 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4210 // GDB has trouble finding local variables in anonymous unions, so we emit
4211 // artificial local variables for each of the members.
4213 // FIXME: Remove this code as soon as GDB supports this.
4214 // The debug info verifier in LLVM operates based on the assumption that a
4215 // variable has the same size as its storage and we had to disable the
4216 // check for artificial variables.
4217 for (const auto *Field : RD->fields()) {
4218 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4219 StringRef FieldName = Field->getName();
4221 // Ignore unnamed fields. Do not ignore unnamed records.
4222 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4225 // Use VarDecl's Tag, Scope and Line number.
4226 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4227 auto *D = DBuilder.createAutoVariable(
4228 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4229 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4231 // Insert an llvm.dbg.declare into the current block.
4232 DBuilder.insertDeclare(
4233 Storage, D, DBuilder.createExpression(Expr),
4234 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4235 Builder.GetInsertBlock());
4240 // Clang stores the sret pointer provided by the caller in a static alloca.
4241 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4242 // the address of the variable.
4243 if (UsePointerValue) {
4244 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4246 "Debug info already contains DW_OP_deref.");
4247 Expr.push_back(llvm::dwarf::DW_OP_deref);
4250 // Create the descriptor for the variable.
4251 auto *D = ArgNo ? DBuilder.createParameterVariable(
4252 Scope, Name, *ArgNo, Unit, Line, Ty,
4253 CGM.getLangOpts().Optimize, Flags)
4254 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4255 CGM.getLangOpts().Optimize,
4258 // Insert an llvm.dbg.declare into the current block.
4259 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4260 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4261 Builder.GetInsertBlock());
4266 llvm::DILocalVariable *
4267 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4268 CGBuilderTy &Builder,
4269 const bool UsePointerValue) {
4270 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4271 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4274 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4275 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4276 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4278 if (D->hasAttr<NoDebugAttr>())
4281 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4282 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4284 // Get location information.
4285 unsigned Line = getLineNumber(D->getLocation());
4286 unsigned Column = getColumnNumber(D->getLocation());
4288 StringRef Name = D->getName();
4290 // Create the descriptor for the label.
4292 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4294 // Insert an llvm.dbg.label into the current block.
4295 DBuilder.insertLabel(L,
4296 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4297 Builder.GetInsertBlock());
4300 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4302 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4305 return DBuilder.createObjectPointerType(Ty);
4308 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4309 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4310 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4311 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4312 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4314 if (Builder.GetInsertBlock() == nullptr)
4316 if (VD->hasAttr<NoDebugAttr>())
4319 bool isByRef = VD->hasAttr<BlocksAttr>();
4321 uint64_t XOffset = 0;
4322 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4325 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4327 Ty = getOrCreateType(VD->getType(), Unit);
4329 // Self is passed along as an implicit non-arg variable in a
4330 // block. Mark it as the object pointer.
4331 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4332 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4333 Ty = CreateSelfType(VD->getType(), Ty);
4335 // Get location information.
4336 unsigned Line = getLineNumber(VD->getLocation());
4337 unsigned Column = getColumnNumber(VD->getLocation());
4339 const llvm::DataLayout &target = CGM.getDataLayout();
4341 CharUnits offset = CharUnits::fromQuantity(
4342 target.getStructLayout(blockInfo.StructureType)
4343 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4345 SmallVector<int64_t, 9> addr;
4346 addr.push_back(llvm::dwarf::DW_OP_deref);
4347 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4348 addr.push_back(offset.getQuantity());
4350 addr.push_back(llvm::dwarf::DW_OP_deref);
4351 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4352 // offset of __forwarding field
4354 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4355 addr.push_back(offset.getQuantity());
4356 addr.push_back(llvm::dwarf::DW_OP_deref);
4357 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4358 // offset of x field
4359 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4360 addr.push_back(offset.getQuantity());
4363 // Create the descriptor for the variable.
4364 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4365 auto *D = DBuilder.createAutoVariable(
4366 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4367 Line, Ty, false, llvm::DINode::FlagZero, Align);
4369 // Insert an llvm.dbg.declare into the current block.
4371 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
4372 auto *Expr = DBuilder.createExpression(addr);
4374 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4376 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4379 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4381 CGBuilderTy &Builder) {
4382 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4383 EmitDeclare(VD, AI, ArgNo, Builder);
4387 struct BlockLayoutChunk {
4388 uint64_t OffsetInBits;
4389 const BlockDecl::Capture *Capture;
4391 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4392 return l.OffsetInBits < r.OffsetInBits;
4396 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4397 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4398 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4399 SmallVectorImpl<llvm::Metadata *> &Fields) {
4400 // Blocks in OpenCL have unique constraints which make the standard fields
4401 // redundant while requiring size and align fields for enqueue_kernel. See
4402 // initializeForBlockHeader in CGBlocks.cpp
4403 if (CGM.getLangOpts().OpenCL) {
4404 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4405 BlockLayout.getElementOffsetInBits(0),
4407 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4408 BlockLayout.getElementOffsetInBits(1),
4411 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4412 BlockLayout.getElementOffsetInBits(0),
4414 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4415 BlockLayout.getElementOffsetInBits(1),
4418 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4419 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4420 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4421 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4422 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4423 BlockLayout.getElementOffsetInBits(3),
4425 Fields.push_back(createFieldType(
4427 Context.getPointerType(Block.NeedsCopyDispose
4428 ? Context.getBlockDescriptorExtendedType()
4429 : Context.getBlockDescriptorType()),
4430 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4434 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4437 llvm::AllocaInst *Alloca,
4438 CGBuilderTy &Builder) {
4439 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4440 ASTContext &C = CGM.getContext();
4441 const BlockDecl *blockDecl = block.getBlockDecl();
4443 // Collect some general information about the block's location.
4444 SourceLocation loc = blockDecl->getCaretLocation();
4445 llvm::DIFile *tunit = getOrCreateFile(loc);
4446 unsigned line = getLineNumber(loc);
4447 unsigned column = getColumnNumber(loc);
4449 // Build the debug-info type for the block literal.
4450 getDeclContextDescriptor(blockDecl);
4452 const llvm::StructLayout *blockLayout =
4453 CGM.getDataLayout().getStructLayout(block.StructureType);
4455 SmallVector<llvm::Metadata *, 16> fields;
4456 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4459 // We want to sort the captures by offset, not because DWARF
4460 // requires this, but because we're paranoid about debuggers.
4461 SmallVector<BlockLayoutChunk, 8> chunks;
4464 if (blockDecl->capturesCXXThis()) {
4465 BlockLayoutChunk chunk;
4466 chunk.OffsetInBits =
4467 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4468 chunk.Capture = nullptr;
4469 chunks.push_back(chunk);
4472 // Variable captures.
4473 for (const auto &capture : blockDecl->captures()) {
4474 const VarDecl *variable = capture.getVariable();
4475 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4477 // Ignore constant captures.
4478 if (captureInfo.isConstant())
4481 BlockLayoutChunk chunk;
4482 chunk.OffsetInBits =
4483 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4484 chunk.Capture = &capture;
4485 chunks.push_back(chunk);
4489 llvm::array_pod_sort(chunks.begin(), chunks.end());
4491 for (const BlockLayoutChunk &Chunk : chunks) {
4492 uint64_t offsetInBits = Chunk.OffsetInBits;
4493 const BlockDecl::Capture *capture = Chunk.Capture;
4495 // If we have a null capture, this must be the C++ 'this' capture.
4499 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4500 type = Method->getThisType();
4501 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4502 type = QualType(RDecl->getTypeForDecl(), 0);
4504 llvm_unreachable("unexpected block declcontext");
4506 fields.push_back(createFieldType("this", type, loc, AS_public,
4507 offsetInBits, tunit, tunit));
4511 const VarDecl *variable = capture->getVariable();
4512 StringRef name = variable->getName();
4514 llvm::DIType *fieldType;
4515 if (capture->isByRef()) {
4516 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4517 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4518 // FIXME: This recomputes the layout of the BlockByRefWrapper.
4521 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4522 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4523 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4524 PtrInfo.Width, Align, offsetInBits,
4525 llvm::DINode::FlagZero, fieldType);
4527 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4528 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4529 offsetInBits, Align, tunit, tunit);
4531 fields.push_back(fieldType);
4534 SmallString<36> typeName;
4535 llvm::raw_svector_ostream(typeName)
4536 << "__block_literal_" << CGM.getUniqueBlockCount();
4538 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4540 llvm::DIType *type =
4541 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4542 CGM.getContext().toBits(block.BlockSize), 0,
4543 llvm::DINode::FlagZero, nullptr, fieldsArray);
4544 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4546 // Get overall information about the block.
4547 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4548 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4550 // Create the descriptor for the parameter.
4551 auto *debugVar = DBuilder.createParameterVariable(
4552 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4554 // Insert an llvm.dbg.declare into the current block.
4555 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4556 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
4557 Builder.GetInsertBlock());
4560 llvm::DIDerivedType *
4561 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4562 if (!D || !D->isStaticDataMember())
4565 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4566 if (MI != StaticDataMemberCache.end()) {
4567 assert(MI->second && "Static data member declaration should still exist");
4571 // If the member wasn't found in the cache, lazily construct and add it to the
4572 // type (used when a limited form of the type is emitted).
4573 auto DC = D->getDeclContext();
4574 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4575 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4578 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4579 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4580 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4581 llvm::DIGlobalVariableExpression *GVE = nullptr;
4583 for (const auto *Field : RD->fields()) {
4584 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4585 StringRef FieldName = Field->getName();
4587 // Ignore unnamed fields, but recurse into anonymous records.
4588 if (FieldName.empty()) {
4589 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4590 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4594 // Use VarDecl's Tag, Scope and Line number.
4595 GVE = DBuilder.createGlobalVariableExpression(
4596 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4597 Var->hasLocalLinkage());
4598 Var->addDebugInfo(GVE);
4603 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4605 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4606 if (D->hasAttr<NoDebugAttr>())
4609 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4611 llvm::raw_string_ostream OS(Name);
4612 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4613 /*Qualified=*/true);
4617 // If we already created a DIGlobalVariable for this declaration, just attach
4618 // it to the llvm::GlobalVariable.
4619 auto Cached = DeclCache.find(D->getCanonicalDecl());
4620 if (Cached != DeclCache.end())
4621 return Var->addDebugInfo(
4622 cast<llvm::DIGlobalVariableExpression>(Cached->second));
4624 // Create global variable debug descriptor.
4625 llvm::DIFile *Unit = nullptr;
4626 llvm::DIScope *DContext = nullptr;
4628 StringRef DeclName, LinkageName;
4630 llvm::MDTuple *TemplateParameters = nullptr;
4631 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4632 TemplateParameters, DContext);
4634 // Attempt to store one global variable for the declaration - even if we
4635 // emit a lot of fields.
4636 llvm::DIGlobalVariableExpression *GVE = nullptr;
4638 // If this is an anonymous union then we'll want to emit a global
4639 // variable for each member of the anonymous union so that it's possible
4640 // to find the name of any field in the union.
4641 if (T->isUnionType() && DeclName.empty()) {
4642 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4643 assert(RD->isAnonymousStructOrUnion() &&
4644 "unnamed non-anonymous struct or union?");
4645 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4647 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4649 SmallVector<int64_t, 4> Expr;
4650 unsigned AddressSpace =
4651 CGM.getContext().getTargetAddressSpace(D->getType());
4652 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4653 if (D->hasAttr<CUDASharedAttr>())
4655 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4656 else if (D->hasAttr<CUDAConstantAttr>())
4658 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4660 AppendAddressSpaceXDeref(AddressSpace, Expr);
4662 GVE = DBuilder.createGlobalVariableExpression(
4663 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4664 Var->hasLocalLinkage(), true,
4665 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4666 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4668 Var->addDebugInfo(GVE);
4670 DeclCache[D->getCanonicalDecl()].reset(GVE);
4673 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4674 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4675 if (VD->hasAttr<NoDebugAttr>())
4677 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4679 llvm::raw_string_ostream OS(Name);
4680 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4681 /*Qualified=*/true);
4685 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4686 // Create the descriptor for the variable.
4687 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4688 StringRef Name = VD->getName();
4689 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4691 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4692 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4693 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4695 if (CGM.getCodeGenOpts().EmitCodeView) {
4696 // If CodeView, emit enums as global variables, unless they are defined
4697 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4698 // enums in classes, and because it is difficult to attach this scope
4699 // information to the global variable.
4700 if (isa<RecordDecl>(ED->getDeclContext()))
4703 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4704 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4705 // first time `ZERO` is referenced in a function.
4706 llvm::DIType *EDTy =
4707 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4708 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4714 llvm::DIScope *DContext = nullptr;
4716 // Do not emit separate definitions for function local consts.
4717 if (isa<FunctionDecl>(VD->getDeclContext()))
4720 // Emit definition for static members in CodeView.
4721 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4722 auto *VarD = dyn_cast<VarDecl>(VD);
4723 if (VarD && VarD->isStaticDataMember()) {
4724 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4725 getDeclContextDescriptor(VarD);
4726 // Ensure that the type is retained even though it's otherwise unreferenced.
4728 // FIXME: This is probably unnecessary, since Ty should reference RD
4729 // through its scope.
4730 RetainedTypes.push_back(
4731 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4733 if (!CGM.getCodeGenOpts().EmitCodeView)
4736 // Use the global scope for static members.
4737 DContext = getContextDescriptor(
4738 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4740 DContext = getDeclContextDescriptor(VD);
4743 auto &GV = DeclCache[VD];
4746 llvm::DIExpression *InitExpr = nullptr;
4747 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4748 // FIXME: Add a representation for integer constants wider than 64 bits.
4751 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4752 else if (Init.isFloat())
4753 InitExpr = DBuilder.createConstantValueExpression(
4754 Init.getFloat().bitcastToAPInt().getZExtValue());
4757 llvm::MDTuple *TemplateParameters = nullptr;
4759 if (isa<VarTemplateSpecializationDecl>(VD))
4761 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4762 TemplateParameters = parameterNodes.get();
4765 GV.reset(DBuilder.createGlobalVariableExpression(
4766 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4767 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4768 TemplateParameters, Align));
4771 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4773 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4774 if (D->hasAttr<NoDebugAttr>())
4777 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4778 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4779 StringRef Name = D->getName();
4780 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4782 llvm::DIScope *DContext = getDeclContextDescriptor(D);
4783 llvm::DIGlobalVariableExpression *GVE =
4784 DBuilder.createGlobalVariableExpression(
4785 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4786 Ty, false, false, nullptr, nullptr, nullptr, Align);
4787 Var->addDebugInfo(GVE);
4790 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4791 if (!LexicalBlockStack.empty())
4792 return LexicalBlockStack.back();
4793 llvm::DIScope *Mod = getParentModuleOrNull(D);
4794 return getContextDescriptor(D, Mod ? Mod : TheCU);
4797 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4798 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4800 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4801 if (!NSDecl->isAnonymousNamespace() ||
4802 CGM.getCodeGenOpts().DebugExplicitImport) {
4803 auto Loc = UD.getLocation();
4804 DBuilder.createImportedModule(
4805 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4806 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4810 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4811 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4813 assert(UD.shadow_size() &&
4814 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4815 // Emitting one decl is sufficient - debuggers can detect that this is an
4816 // overloaded name & provide lookup for all the overloads.
4817 const UsingShadowDecl &USD = **UD.shadow_begin();
4819 // FIXME: Skip functions with undeduced auto return type for now since we
4820 // don't currently have the plumbing for separate declarations & definitions
4821 // of free functions and mismatched types (auto in the declaration, concrete
4822 // return type in the definition)
4823 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4824 if (const auto *AT =
4825 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4826 if (AT->getDeducedType().isNull())
4828 if (llvm::DINode *Target =
4829 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4830 auto Loc = USD.getLocation();
4831 DBuilder.createImportedDeclaration(
4832 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4833 getOrCreateFile(Loc), getLineNumber(Loc));
4837 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4838 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4840 if (Module *M = ID.getImportedModule()) {
4841 auto Info = ASTSourceDescriptor(*M);
4842 auto Loc = ID.getLocation();
4843 DBuilder.createImportedDeclaration(
4844 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4845 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4846 getLineNumber(Loc));
4850 llvm::DIImportedEntity *
4851 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4852 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4854 auto &VH = NamespaceAliasCache[&NA];
4856 return cast<llvm::DIImportedEntity>(VH);
4857 llvm::DIImportedEntity *R;
4858 auto Loc = NA.getLocation();
4859 if (const auto *Underlying =
4860 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4861 // This could cache & dedup here rather than relying on metadata deduping.
4862 R = DBuilder.createImportedDeclaration(
4863 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4864 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4865 getLineNumber(Loc), NA.getName());
4867 R = DBuilder.createImportedDeclaration(
4868 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4869 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4870 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4876 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4877 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4878 // if necessary, and this way multiple declarations of the same namespace in
4879 // different parent modules stay distinct.
4880 auto I = NamespaceCache.find(NSDecl);
4881 if (I != NamespaceCache.end())
4882 return cast<llvm::DINamespace>(I->second);
4884 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4885 // Don't trust the context if it is a DIModule (see comment above).
4886 llvm::DINamespace *NS =
4887 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4888 NamespaceCache[NSDecl].reset(NS);
4892 void CGDebugInfo::setDwoId(uint64_t Signature) {
4893 assert(TheCU && "no main compile unit");
4894 TheCU->setDWOId(Signature);
4897 void CGDebugInfo::finalize() {
4898 // Creating types might create further types - invalidating the current
4899 // element and the size(), so don't cache/reference them.
4900 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4901 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4902 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4903 ? CreateTypeDefinition(E.Type, E.Unit)
4905 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4908 // Add methods to interface.
4909 for (const auto &P : ObjCMethodCache) {
4910 if (P.second.empty())
4913 QualType QTy(P.first->getTypeForDecl(), 0);
4914 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4915 assert(It != TypeCache.end());
4917 llvm::DICompositeType *InterfaceDecl =
4918 cast<llvm::DICompositeType>(It->second);
4920 auto CurElts = InterfaceDecl->getElements();
4921 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4923 // For DWARF v4 or earlier, only add objc_direct methods.
4924 for (auto &SubprogramDirect : P.second)
4925 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4926 EltTys.push_back(SubprogramDirect.getPointer());
4928 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4929 DBuilder.replaceArrays(InterfaceDecl, Elements);
4932 for (const auto &P : ReplaceMap) {
4934 auto *Ty = cast<llvm::DIType>(P.second);
4935 assert(Ty->isForwardDecl());
4937 auto It = TypeCache.find(P.first);
4938 assert(It != TypeCache.end());
4941 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4942 cast<llvm::DIType>(It->second));
4945 for (const auto &P : FwdDeclReplaceMap) {
4947 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4948 llvm::Metadata *Repl;
4950 auto It = DeclCache.find(P.first);
4951 // If there has been no definition for the declaration, call RAUW
4952 // with ourselves, that will destroy the temporary MDNode and
4953 // replace it with a standard one, avoiding leaking memory.
4954 if (It == DeclCache.end())
4959 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4960 Repl = GVE->getVariable();
4961 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4964 // We keep our own list of retained types, because we need to look
4965 // up the final type in the type cache.
4966 for (auto &RT : RetainedTypes)
4967 if (auto MD = TypeCache[RT])
4968 DBuilder.retainType(cast<llvm::DIType>(MD));
4970 DBuilder.finalize();
4973 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4974 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4977 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
4978 // Don't ignore in case of explicit cast where it is referenced indirectly.
4979 DBuilder.retainType(DieTy);
4982 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4983 if (LexicalBlockStack.empty())
4984 return llvm::DebugLoc();
4986 llvm::MDNode *Scope = LexicalBlockStack.back();
4987 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
4990 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4991 // Call site-related attributes are only useful in optimized programs, and
4992 // when there's a possibility of debugging backtraces.
4993 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4994 DebugKind == codegenoptions::LocTrackingOnly)
4995 return llvm::DINode::FlagZero;
4997 // Call site-related attributes are available in DWARF v5. Some debuggers,
4998 // while not fully DWARF v5-compliant, may accept these attributes as if they
4999 // were part of DWARF v4.
5000 bool SupportsDWARFv4Ext =
5001 CGM.getCodeGenOpts().DwarfVersion == 4 &&
5002 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
5003 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
5005 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
5006 return llvm::DINode::FlagZero;
5008 return llvm::DINode::FlagAllCallsDescribed;