1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "clang/AST/ASTContext.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/FileManager.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Frontend/CodeGenOptions.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/Module.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/MD5.h"
47 #include "llvm/Support/Path.h"
48 using namespace clang;
49 using namespace clang::CodeGen;
51 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
52 auto TI = Ctx.getTypeInfo(Ty);
53 return TI.AlignIsRequired ? TI.Align : 0;
56 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
57 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
60 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
61 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
64 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
65 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
66 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
67 DBuilder(CGM.getModule()) {
68 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
69 DebugPrefixMap[KV.first] = KV.second;
73 CGDebugInfo::~CGDebugInfo() {
74 assert(LexicalBlockStack.empty() &&
75 "Region stack mismatch, stack not empty!");
78 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
79 SourceLocation TemporaryLocation)
81 init(TemporaryLocation);
84 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
86 SourceLocation TemporaryLocation)
88 init(TemporaryLocation, DefaultToEmpty);
91 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
92 bool DefaultToEmpty) {
93 auto *DI = CGF->getDebugInfo();
99 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
101 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
104 if (TemporaryLocation.isValid()) {
105 DI->EmitLocation(CGF->Builder, TemporaryLocation);
109 if (DefaultToEmpty) {
110 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
114 // Construct a location that has a valid scope, but no line info.
115 assert(!DI->LexicalBlockStack.empty());
116 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
117 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
120 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
122 init(E->getExprLoc());
125 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
127 if (!CGF.getDebugInfo()) {
131 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
133 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
136 ApplyDebugLocation::~ApplyDebugLocation() {
137 // Query CGF so the location isn't overwritten when location updates are
138 // temporarily disabled (for C++ default function arguments)
140 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
143 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
144 GlobalDecl InlinedFn)
146 if (!CGF.getDebugInfo()) {
150 auto &DI = *CGF.getDebugInfo();
151 SavedLocation = DI.getLocation();
152 assert((DI.getInlinedAt() ==
153 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
154 "CGDebugInfo and IRBuilder are out of sync");
156 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
159 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
162 auto &DI = *CGF->getDebugInfo();
163 DI.EmitInlineFunctionEnd(CGF->Builder);
164 DI.EmitLocation(CGF->Builder, SavedLocation);
167 void CGDebugInfo::setLocation(SourceLocation Loc) {
168 // If the new location isn't valid return.
172 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
174 // If we've changed files in the middle of a lexical scope go ahead
175 // and create a new lexical scope with file node if it's different
176 // from the one in the scope.
177 if (LexicalBlockStack.empty())
180 SourceManager &SM = CGM.getContext().getSourceManager();
181 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
182 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
184 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
187 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
188 LexicalBlockStack.pop_back();
189 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
190 LBF->getScope(), getOrCreateFile(CurLoc)));
191 } else if (isa<llvm::DILexicalBlock>(Scope) ||
192 isa<llvm::DISubprogram>(Scope)) {
193 LexicalBlockStack.pop_back();
194 LexicalBlockStack.emplace_back(
195 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
199 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
200 llvm::DIScope *Mod = getParentModuleOrNull(D);
201 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
205 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
206 llvm::DIScope *Default) {
210 auto I = RegionMap.find(Context);
211 if (I != RegionMap.end()) {
212 llvm::Metadata *V = I->second;
213 return dyn_cast_or_null<llvm::DIScope>(V);
217 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
218 return getOrCreateNamespace(NSDecl);
220 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
221 if (!RDecl->isDependentType())
222 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
223 getOrCreateMainFile());
227 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
228 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
230 // If we're emitting codeview, it's important to try to match MSVC's naming so
231 // that visualizers written for MSVC will trigger for our class names. In
232 // particular, we can't have spaces between arguments of standard templates
233 // like basic_string and vector.
234 if (CGM.getCodeGenOpts().EmitCodeView)
235 PP.MSVCFormatting = true;
240 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
241 assert(FD && "Invalid FunctionDecl!");
242 IdentifierInfo *FII = FD->getIdentifier();
243 FunctionTemplateSpecializationInfo *Info =
244 FD->getTemplateSpecializationInfo();
246 // Emit the unqualified name in normal operation. LLVM and the debugger can
247 // compute the fully qualified name from the scope chain. If we're only
248 // emitting line table info, there won't be any scope chains, so emit the
249 // fully qualified name here so that stack traces are more accurate.
250 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
251 // evaluating the size impact.
252 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
253 CGM.getCodeGenOpts().EmitCodeView;
255 if (!Info && FII && !UseQualifiedName)
256 return FII->getName();
259 llvm::raw_svector_ostream OS(NS);
260 if (!UseQualifiedName)
263 FD->printQualifiedName(OS, getPrintingPolicy());
265 // Add any template specialization args.
267 const TemplateArgumentList *TArgs = Info->TemplateArguments;
268 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
271 // Copy this name on the side and use its reference.
272 return internString(OS.str());
275 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
276 SmallString<256> MethodName;
277 llvm::raw_svector_ostream OS(MethodName);
278 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
279 const DeclContext *DC = OMD->getDeclContext();
280 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
281 OS << OID->getName();
282 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
283 OS << OID->getName();
284 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
285 if (OC->IsClassExtension()) {
286 OS << OC->getClassInterface()->getName();
288 OS << OC->getIdentifier()->getNameStart() << '('
289 << OC->getIdentifier()->getNameStart() << ')';
291 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
292 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
293 } else if (isa<ObjCProtocolDecl>(DC)) {
294 // We can extract the type of the class from the self pointer.
295 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
297 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
298 ClassTy.print(OS, PrintingPolicy(LangOptions()));
301 OS << ' ' << OMD->getSelector().getAsString() << ']';
303 return internString(OS.str());
306 StringRef CGDebugInfo::getSelectorName(Selector S) {
307 return internString(S.getAsString());
310 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
311 if (isa<ClassTemplateSpecializationDecl>(RD)) {
312 SmallString<128> Name;
313 llvm::raw_svector_ostream OS(Name);
314 RD->getNameForDiagnostic(OS, getPrintingPolicy(),
315 /*Qualified*/ false);
317 // Copy this name on the side and use its reference.
318 return internString(Name);
321 // quick optimization to avoid having to intern strings that are already
322 // stored reliably elsewhere
323 if (const IdentifierInfo *II = RD->getIdentifier())
324 return II->getName();
326 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
327 // used to reconstruct the fully qualified type names.
328 if (CGM.getCodeGenOpts().EmitCodeView) {
329 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
330 assert(RD->getDeclContext() == D->getDeclContext() &&
331 "Typedef should not be in another decl context!");
332 assert(D->getDeclName().getAsIdentifierInfo() &&
333 "Typedef was not named!");
334 return D->getDeclName().getAsIdentifierInfo()->getName();
337 if (CGM.getLangOpts().CPlusPlus) {
340 ASTContext &Context = CGM.getContext();
341 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
342 // Anonymous types without a name for linkage purposes have their
343 // declarator mangled in if they have one.
344 Name = DD->getName();
345 else if (const TypedefNameDecl *TND =
346 Context.getTypedefNameForUnnamedTagDecl(RD))
347 // Anonymous types without a name for linkage purposes have their
348 // associate typedef mangled in if they have one.
349 Name = TND->getName();
352 SmallString<256> UnnamedType("<unnamed-type-");
355 return internString(UnnamedType);
363 Optional<llvm::DIFile::ChecksumKind>
364 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
367 if (!CGM.getCodeGenOpts().EmitCodeView &&
368 CGM.getCodeGenOpts().DwarfVersion < 5)
371 SourceManager &SM = CGM.getContext().getSourceManager();
373 llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
378 llvm::MD5::MD5Result Result;
380 Hash.update(MemBuffer->getBuffer());
383 Hash.stringifyResult(Result, Checksum);
384 return llvm::DIFile::CSK_MD5;
387 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
389 if (!CGM.getCodeGenOpts().EmbedSource)
392 bool SourceInvalid = false;
393 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
401 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
403 // If Location is not valid then use main input file.
404 return getOrCreateMainFile();
406 SourceManager &SM = CGM.getContext().getSourceManager();
407 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
409 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
410 // If the location is not valid then use main input file.
411 return getOrCreateMainFile();
413 // Cache the results.
414 const char *fname = PLoc.getFilename();
415 auto It = DIFileCache.find(fname);
417 if (It != DIFileCache.end()) {
418 // Verify that the information still exists.
419 if (llvm::Metadata *V = It->second)
420 return cast<llvm::DIFile>(V);
423 SmallString<32> Checksum;
424 Optional<llvm::DIFile::ChecksumKind> CSKind =
425 computeChecksum(SM.getFileID(Loc), Checksum);
426 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
428 CSInfo.emplace(*CSKind, Checksum);
430 llvm::DIFile *F = DBuilder.createFile(
431 remapDIPath(PLoc.getFilename()), remapDIPath(getCurrentDirname()), CSInfo,
432 getSource(SM, SM.getFileID(Loc)));
434 DIFileCache[fname].reset(F);
438 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
439 return DBuilder.createFile(
440 remapDIPath(TheCU->getFilename()), remapDIPath(TheCU->getDirectory()),
441 TheCU->getFile()->getChecksum(),
442 CGM.getCodeGenOpts().EmbedSource ? TheCU->getSource() : None);
445 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
446 for (const auto &Entry : DebugPrefixMap)
447 if (Path.startswith(Entry.first))
448 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
452 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
453 if (Loc.isInvalid() && CurLoc.isInvalid())
455 SourceManager &SM = CGM.getContext().getSourceManager();
456 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
457 return PLoc.isValid() ? PLoc.getLine() : 0;
460 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
461 // We may not want column information at all.
462 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
465 // If the location is invalid then use the current column.
466 if (Loc.isInvalid() && CurLoc.isInvalid())
468 SourceManager &SM = CGM.getContext().getSourceManager();
469 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
470 return PLoc.isValid() ? PLoc.getColumn() : 0;
473 StringRef CGDebugInfo::getCurrentDirname() {
474 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
475 return CGM.getCodeGenOpts().DebugCompilationDir;
477 if (!CWDName.empty())
479 SmallString<256> CWD;
480 llvm::sys::fs::current_path(CWD);
481 return CWDName = internString(CWD);
484 void CGDebugInfo::CreateCompileUnit() {
485 SmallString<32> Checksum;
486 Optional<llvm::DIFile::ChecksumKind> CSKind;
487 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
489 // Should we be asking the SourceManager for the main file name, instead of
490 // accepting it as an argument? This just causes the main file name to
491 // mismatch with source locations and create extra lexical scopes or
492 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
493 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
494 // because that's what the SourceManager says)
496 // Get absolute path name.
497 SourceManager &SM = CGM.getContext().getSourceManager();
498 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
499 if (MainFileName.empty())
500 MainFileName = "<stdin>";
502 // The main file name provided via the "-main-file-name" option contains just
503 // the file name itself with no path information. This file name may have had
504 // a relative path, so we look into the actual file entry for the main
505 // file to determine the real absolute path for the file.
506 std::string MainFileDir;
507 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
508 MainFileDir = remapDIPath(MainFile->getDir()->getName());
509 if (MainFileDir != ".") {
510 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
511 llvm::sys::path::append(MainFileDirSS, MainFileName);
512 MainFileName = MainFileDirSS.str();
514 // If the main file name provided is identical to the input file name, and
515 // if the input file is a preprocessed source, use the module name for
516 // debug info. The module name comes from the name specified in the first
517 // linemarker if the input is a preprocessed source.
518 if (MainFile->getName() == MainFileName &&
519 FrontendOptions::getInputKindForExtension(
520 MainFile->getName().rsplit('.').second)
522 MainFileName = CGM.getModule().getName().str();
524 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
527 llvm::dwarf::SourceLanguage LangTag;
528 const LangOptions &LO = CGM.getLangOpts();
531 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
533 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
534 } else if (LO.ObjC1) {
535 LangTag = llvm::dwarf::DW_LANG_ObjC;
536 } else if (LO.RenderScript) {
537 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
539 LangTag = llvm::dwarf::DW_LANG_C99;
541 LangTag = llvm::dwarf::DW_LANG_C89;
544 std::string Producer = getClangFullVersion();
546 // Figure out which version of the ObjC runtime we have.
547 unsigned RuntimeVers = 0;
549 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
551 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
553 case codegenoptions::NoDebugInfo:
554 case codegenoptions::LocTrackingOnly:
555 EmissionKind = llvm::DICompileUnit::NoDebug;
557 case codegenoptions::DebugLineTablesOnly:
558 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
560 case codegenoptions::LimitedDebugInfo:
561 case codegenoptions::FullDebugInfo:
562 EmissionKind = llvm::DICompileUnit::FullDebug;
567 CSInfo.emplace(*CSKind, Checksum);
569 // Create new compile unit.
570 // FIXME - Eliminate TheCU.
571 auto &CGOpts = CGM.getCodeGenOpts();
572 TheCU = DBuilder.createCompileUnit(
574 DBuilder.createFile(remapDIPath(MainFileName),
575 remapDIPath(getCurrentDirname()), CSInfo,
576 getSource(SM, SM.getMainFileID())),
577 CGOpts.EmitVersionIdentMetadata ? Producer : "",
578 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
579 CGOpts.DwarfDebugFlags, RuntimeVers,
580 CGOpts.EnableSplitDwarf ? "" : CGOpts.SplitDwarfFile, EmissionKind,
581 0 /* DWOid */, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
585 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
586 llvm::dwarf::TypeKind Encoding;
588 switch (BT->getKind()) {
589 #define BUILTIN_TYPE(Id, SingletonId)
590 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
591 #include "clang/AST/BuiltinTypes.def"
592 case BuiltinType::Dependent:
593 llvm_unreachable("Unexpected builtin type");
594 case BuiltinType::NullPtr:
595 return DBuilder.createNullPtrType();
596 case BuiltinType::Void:
598 case BuiltinType::ObjCClass:
600 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
602 getOrCreateMainFile(), 0);
604 case BuiltinType::ObjCId: {
605 // typedef struct objc_class *Class;
606 // typedef struct objc_object {
614 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
616 getOrCreateMainFile(), 0);
618 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
620 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
622 ObjTy = DBuilder.createStructType(
623 TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
624 llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
626 DBuilder.replaceArrays(
627 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
628 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
629 llvm::DINode::FlagZero, ISATy)));
632 case BuiltinType::ObjCSel: {
634 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
635 "objc_selector", TheCU,
636 getOrCreateMainFile(), 0);
640 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
641 case BuiltinType::Id: \
642 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
644 #include "clang/Basic/OpenCLImageTypes.def"
645 case BuiltinType::OCLSampler:
646 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
647 case BuiltinType::OCLEvent:
648 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
649 case BuiltinType::OCLClkEvent:
650 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
651 case BuiltinType::OCLQueue:
652 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
653 case BuiltinType::OCLReserveID:
654 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
656 case BuiltinType::UChar:
657 case BuiltinType::Char_U:
658 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
660 case BuiltinType::Char_S:
661 case BuiltinType::SChar:
662 Encoding = llvm::dwarf::DW_ATE_signed_char;
664 case BuiltinType::Char8:
665 case BuiltinType::Char16:
666 case BuiltinType::Char32:
667 Encoding = llvm::dwarf::DW_ATE_UTF;
669 case BuiltinType::UShort:
670 case BuiltinType::UInt:
671 case BuiltinType::UInt128:
672 case BuiltinType::ULong:
673 case BuiltinType::WChar_U:
674 case BuiltinType::ULongLong:
675 Encoding = llvm::dwarf::DW_ATE_unsigned;
677 case BuiltinType::Short:
678 case BuiltinType::Int:
679 case BuiltinType::Int128:
680 case BuiltinType::Long:
681 case BuiltinType::WChar_S:
682 case BuiltinType::LongLong:
683 Encoding = llvm::dwarf::DW_ATE_signed;
685 case BuiltinType::Bool:
686 Encoding = llvm::dwarf::DW_ATE_boolean;
688 case BuiltinType::Half:
689 case BuiltinType::Float:
690 case BuiltinType::LongDouble:
691 case BuiltinType::Float16:
692 case BuiltinType::Float128:
693 case BuiltinType::Double:
694 // FIXME: For targets where long double and __float128 have the same size,
695 // they are currently indistinguishable in the debugger without some
696 // special treatment. However, there is currently no consensus on encoding
697 // and this should be updated once a DWARF encoding exists for distinct
698 // floating point types of the same size.
699 Encoding = llvm::dwarf::DW_ATE_float;
701 case BuiltinType::ShortAccum:
702 case BuiltinType::Accum:
703 case BuiltinType::LongAccum:
704 case BuiltinType::ShortFract:
705 case BuiltinType::Fract:
706 case BuiltinType::LongFract:
707 case BuiltinType::SatShortFract:
708 case BuiltinType::SatFract:
709 case BuiltinType::SatLongFract:
710 case BuiltinType::SatShortAccum:
711 case BuiltinType::SatAccum:
712 case BuiltinType::SatLongAccum:
713 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
715 case BuiltinType::UShortAccum:
716 case BuiltinType::UAccum:
717 case BuiltinType::ULongAccum:
718 case BuiltinType::UShortFract:
719 case BuiltinType::UFract:
720 case BuiltinType::ULongFract:
721 case BuiltinType::SatUShortAccum:
722 case BuiltinType::SatUAccum:
723 case BuiltinType::SatULongAccum:
724 case BuiltinType::SatUShortFract:
725 case BuiltinType::SatUFract:
726 case BuiltinType::SatULongFract:
727 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
731 switch (BT->getKind()) {
732 case BuiltinType::Long:
735 case BuiltinType::LongLong:
736 BTName = "long long int";
738 case BuiltinType::ULong:
739 BTName = "long unsigned int";
741 case BuiltinType::ULongLong:
742 BTName = "long long unsigned int";
745 BTName = BT->getName(CGM.getLangOpts());
748 // Bit size and offset of the type.
749 uint64_t Size = CGM.getContext().getTypeSize(BT);
750 return DBuilder.createBasicType(BTName, Size, Encoding);
753 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
754 // Bit size and offset of the type.
755 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
756 if (Ty->isComplexIntegerType())
757 Encoding = llvm::dwarf::DW_ATE_lo_user;
759 uint64_t Size = CGM.getContext().getTypeSize(Ty);
760 return DBuilder.createBasicType("complex", Size, Encoding);
763 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
764 llvm::DIFile *Unit) {
765 QualifierCollector Qc;
766 const Type *T = Qc.strip(Ty);
768 // Ignore these qualifiers for now.
769 Qc.removeObjCGCAttr();
770 Qc.removeAddressSpace();
771 Qc.removeObjCLifetime();
773 // We will create one Derived type for one qualifier and recurse to handle any
775 llvm::dwarf::Tag Tag;
777 Tag = llvm::dwarf::DW_TAG_const_type;
779 } else if (Qc.hasVolatile()) {
780 Tag = llvm::dwarf::DW_TAG_volatile_type;
782 } else if (Qc.hasRestrict()) {
783 Tag = llvm::dwarf::DW_TAG_restrict_type;
786 assert(Qc.empty() && "Unknown type qualifier for debug info");
787 return getOrCreateType(QualType(T, 0), Unit);
790 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
792 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
793 // CVR derived types.
794 return DBuilder.createQualifiedType(Tag, FromTy);
797 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
798 llvm::DIFile *Unit) {
800 // The frontend treats 'id' as a typedef to an ObjCObjectType,
801 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
802 // debug info, we want to emit 'id' in both cases.
803 if (Ty->isObjCQualifiedIdType())
804 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
806 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
807 Ty->getPointeeType(), Unit);
810 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
811 llvm::DIFile *Unit) {
812 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
813 Ty->getPointeeType(), Unit);
816 /// \return whether a C++ mangling exists for the type defined by TD.
817 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
818 switch (TheCU->getSourceLanguage()) {
819 case llvm::dwarf::DW_LANG_C_plus_plus:
821 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
822 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
828 // Determines if the tag declaration will require a type identifier.
829 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
830 llvm::DICompileUnit *TheCU) {
831 // We only add a type identifier for types with C++ name mangling.
832 if (!hasCXXMangling(TD, TheCU))
835 // CodeView types with C++ mangling need a type identifier.
836 if (CGM.getCodeGenOpts().EmitCodeView)
839 // Externally visible types with C++ mangling need a type identifier.
840 if (TD->isExternallyVisible())
846 // When emitting CodeView debug information we need to produce a type
847 // identifier for all types which have a C++ mangling. Until a GUID is added
848 // to the identifier (not currently implemented) the result will not be unique
849 // across compilation units.
850 // When emitting DWARF debug information, we need to produce a type identifier
851 // for all externally visible types with C++ name mangling. This identifier
852 // should be unique across ODR-compliant compilation units.
853 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
854 llvm::DICompileUnit *TheCU) {
855 SmallString<256> Identifier;
856 const TagDecl *TD = Ty->getDecl();
858 if (!needsTypeIdentifier(TD, CGM, TheCU))
861 // TODO: This is using the RTTI name. Is there a better way to get
862 // a unique string for a type?
863 llvm::raw_svector_ostream Out(Identifier);
864 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
868 /// \return the appropriate DWARF tag for a composite type.
869 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
870 llvm::dwarf::Tag Tag;
871 if (RD->isStruct() || RD->isInterface())
872 Tag = llvm::dwarf::DW_TAG_structure_type;
873 else if (RD->isUnion())
874 Tag = llvm::dwarf::DW_TAG_union_type;
876 // FIXME: This could be a struct type giving a default visibility different
877 // than C++ class type, but needs llvm metadata changes first.
878 assert(RD->isClass());
879 Tag = llvm::dwarf::DW_TAG_class_type;
884 llvm::DICompositeType *
885 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
886 llvm::DIScope *Ctx) {
887 const RecordDecl *RD = Ty->getDecl();
888 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
889 return cast<llvm::DICompositeType>(T);
890 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
891 unsigned Line = getLineNumber(RD->getLocation());
892 StringRef RDName = getClassName(RD);
898 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
899 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
900 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
901 llvm::DINode::FlagFwdDecl, Identifier);
902 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
903 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
904 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
905 CollectCXXTemplateParams(TSpecial, DefUnit));
906 ReplaceMap.emplace_back(
907 std::piecewise_construct, std::make_tuple(Ty),
908 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
912 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
915 llvm::DIFile *Unit) {
916 // Bit size, align and offset of the type.
917 // Size is always the size of a pointer. We can't use getTypeSize here
918 // because that does not return the correct value for references.
919 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
920 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
921 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
922 Optional<unsigned> DWARFAddressSpace =
923 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
925 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
926 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
927 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
928 Size, Align, DWARFAddressSpace);
930 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
931 Align, DWARFAddressSpace);
934 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
935 llvm::DIType *&Cache) {
938 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
939 TheCU, getOrCreateMainFile(), 0);
940 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
941 Cache = DBuilder.createPointerType(Cache, Size);
945 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
946 llvm::DIFile *Unit) {
947 SmallVector<llvm::Metadata *, 8> EltTys;
949 uint64_t FieldSize, FieldOffset;
951 llvm::DINodeArray Elements;
954 FType = CGM.getContext().UnsignedLongTy;
955 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
956 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
958 Elements = DBuilder.getOrCreateArray(EltTys);
961 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
965 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
966 FieldOffset, 0, Flags, nullptr, Elements);
968 // Bit size, align and offset of the type.
969 uint64_t Size = CGM.getContext().getTypeSize(Ty);
971 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
974 if (CGM.getLangOpts().OpenCL) {
975 FType = CGM.getContext().IntTy;
976 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
977 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
979 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
980 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
981 FType = CGM.getContext().IntTy;
982 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
983 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
984 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
985 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
986 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
987 FieldSize = CGM.getContext().getTypeSize(Ty);
988 FieldAlign = CGM.getContext().getTypeAlign(Ty);
989 EltTys.push_back(DBuilder.createMemberType(
990 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset,
991 llvm::DINode::FlagZero, DescTy));
992 FieldOffset += FieldSize;
995 Elements = DBuilder.getOrCreateArray(EltTys);
997 // The __block_literal_generic structs are marked with a special
998 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
999 // the debugger needs to know about. To allow type uniquing, emit
1000 // them without a name or a location.
1001 EltTy = DBuilder.createStructType(Unit, "", nullptr, LineNo, FieldOffset, 0,
1002 Flags, nullptr, Elements);
1004 return DBuilder.createPointerType(EltTy, Size);
1007 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1008 llvm::DIFile *Unit) {
1009 assert(Ty->isTypeAlias());
1010 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1012 SmallString<128> NS;
1013 llvm::raw_svector_ostream OS(NS);
1014 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1015 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1018 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1019 ->getTemplatedDecl();
1021 SourceLocation Loc = AliasDecl->getLocation();
1022 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1024 getDeclContextDescriptor(AliasDecl));
1027 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1028 llvm::DIFile *Unit) {
1029 // We don't set size information, but do specify where the typedef was
1031 SourceLocation Loc = Ty->getDecl()->getLocation();
1033 // Typedefs are derived from some other type.
1034 return DBuilder.createTypedef(
1035 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
1036 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
1037 getDeclContextDescriptor(Ty->getDecl()));
1040 static unsigned getDwarfCC(CallingConv CC) {
1043 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1047 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1048 case CC_X86FastCall:
1049 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1050 case CC_X86ThisCall:
1051 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1052 case CC_X86VectorCall:
1053 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1055 return llvm::dwarf::DW_CC_BORLAND_pascal;
1057 return llvm::dwarf::DW_CC_LLVM_Win64;
1059 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1061 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1063 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1064 case CC_IntelOclBicc:
1065 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1066 case CC_SpirFunction:
1067 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1068 case CC_OpenCLKernel:
1069 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1071 return llvm::dwarf::DW_CC_LLVM_Swift;
1072 case CC_PreserveMost:
1073 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1074 case CC_PreserveAll:
1075 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1077 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1082 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1083 llvm::DIFile *Unit) {
1084 SmallVector<llvm::Metadata *, 16> EltTys;
1086 // Add the result type at least.
1087 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1089 // Set up remainder of arguments if there is a prototype.
1090 // otherwise emit it as a variadic function.
1091 if (isa<FunctionNoProtoType>(Ty))
1092 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1093 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1094 for (const QualType &ParamType : FPT->param_types())
1095 EltTys.push_back(getOrCreateType(ParamType, Unit));
1096 if (FPT->isVariadic())
1097 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1100 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1101 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1102 getDwarfCC(Ty->getCallConv()));
1105 /// Convert an AccessSpecifier into the corresponding DINode flag.
1106 /// As an optimization, return 0 if the access specifier equals the
1107 /// default for the containing type.
1108 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1109 const RecordDecl *RD) {
1110 AccessSpecifier Default = clang::AS_none;
1111 if (RD && RD->isClass())
1112 Default = clang::AS_private;
1113 else if (RD && (RD->isStruct() || RD->isUnion()))
1114 Default = clang::AS_public;
1116 if (Access == Default)
1117 return llvm::DINode::FlagZero;
1120 case clang::AS_private:
1121 return llvm::DINode::FlagPrivate;
1122 case clang::AS_protected:
1123 return llvm::DINode::FlagProtected;
1124 case clang::AS_public:
1125 return llvm::DINode::FlagPublic;
1126 case clang::AS_none:
1127 return llvm::DINode::FlagZero;
1129 llvm_unreachable("unexpected access enumerator");
1132 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1133 llvm::DIScope *RecordTy,
1134 const RecordDecl *RD) {
1135 StringRef Name = BitFieldDecl->getName();
1136 QualType Ty = BitFieldDecl->getType();
1137 SourceLocation Loc = BitFieldDecl->getLocation();
1138 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1139 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1141 // Get the location for the field.
1142 llvm::DIFile *File = getOrCreateFile(Loc);
1143 unsigned Line = getLineNumber(Loc);
1145 const CGBitFieldInfo &BitFieldInfo =
1146 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1147 uint64_t SizeInBits = BitFieldInfo.Size;
1148 assert(SizeInBits > 0 && "found named 0-width bitfield");
1149 uint64_t StorageOffsetInBits =
1150 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1151 uint64_t Offset = BitFieldInfo.Offset;
1152 // The bit offsets for big endian machines are reversed for big
1153 // endian target, compensate for that as the DIDerivedType requires
1154 // un-reversed offsets.
1155 if (CGM.getDataLayout().isBigEndian())
1156 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1157 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1158 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1159 return DBuilder.createBitFieldMemberType(
1160 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1165 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1166 AccessSpecifier AS, uint64_t offsetInBits,
1167 uint32_t AlignInBits, llvm::DIFile *tunit,
1168 llvm::DIScope *scope, const RecordDecl *RD) {
1169 llvm::DIType *debugType = getOrCreateType(type, tunit);
1171 // Get the location for the field.
1172 llvm::DIFile *file = getOrCreateFile(loc);
1173 unsigned line = getLineNumber(loc);
1175 uint64_t SizeInBits = 0;
1176 auto Align = AlignInBits;
1177 if (!type->isIncompleteArrayType()) {
1178 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1179 SizeInBits = TI.Width;
1181 Align = getTypeAlignIfRequired(type, CGM.getContext());
1184 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1185 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1186 offsetInBits, flags, debugType);
1189 void CGDebugInfo::CollectRecordLambdaFields(
1190 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1191 llvm::DIType *RecordTy) {
1192 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1193 // has the name and the location of the variable so we should iterate over
1194 // both concurrently.
1195 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1196 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1197 unsigned fieldno = 0;
1198 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1199 E = CXXDecl->captures_end();
1200 I != E; ++I, ++Field, ++fieldno) {
1201 const LambdaCapture &C = *I;
1202 if (C.capturesVariable()) {
1203 SourceLocation Loc = C.getLocation();
1204 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1205 VarDecl *V = C.getCapturedVar();
1206 StringRef VName = V->getName();
1207 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1208 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1209 llvm::DIType *FieldType = createFieldType(
1210 VName, Field->getType(), Loc, Field->getAccess(),
1211 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1212 elements.push_back(FieldType);
1213 } else if (C.capturesThis()) {
1214 // TODO: Need to handle 'this' in some way by probably renaming the
1215 // this of the lambda class and having a field member of 'this' or
1216 // by using AT_object_pointer for the function and having that be
1217 // used as 'this' for semantic references.
1218 FieldDecl *f = *Field;
1219 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1220 QualType type = f->getType();
1221 llvm::DIType *fieldType = createFieldType(
1222 "this", type, f->getLocation(), f->getAccess(),
1223 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1225 elements.push_back(fieldType);
1230 llvm::DIDerivedType *
1231 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1232 const RecordDecl *RD) {
1233 // Create the descriptor for the static variable, with or without
1234 // constant initializers.
1235 Var = Var->getCanonicalDecl();
1236 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1237 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1239 unsigned LineNumber = getLineNumber(Var->getLocation());
1240 StringRef VName = Var->getName();
1241 llvm::Constant *C = nullptr;
1242 if (Var->getInit()) {
1243 const APValue *Value = Var->evaluateValue();
1246 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1247 if (Value->isFloat())
1248 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1252 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1253 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1254 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1255 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1256 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1260 void CGDebugInfo::CollectRecordNormalField(
1261 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1262 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1263 const RecordDecl *RD) {
1264 StringRef name = field->getName();
1265 QualType type = field->getType();
1267 // Ignore unnamed fields unless they're anonymous structs/unions.
1268 if (name.empty() && !type->isRecordType())
1271 llvm::DIType *FieldType;
1272 if (field->isBitField()) {
1273 FieldType = createBitFieldType(field, RecordTy, RD);
1275 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1277 createFieldType(name, type, field->getLocation(), field->getAccess(),
1278 OffsetInBits, Align, tunit, RecordTy, RD);
1281 elements.push_back(FieldType);
1284 void CGDebugInfo::CollectRecordNestedType(
1285 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1286 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1287 // Injected class names are not considered nested records.
1288 if (isa<InjectedClassNameType>(Ty))
1290 SourceLocation Loc = TD->getLocation();
1291 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1292 elements.push_back(nestedType);
1295 void CGDebugInfo::CollectRecordFields(
1296 const RecordDecl *record, llvm::DIFile *tunit,
1297 SmallVectorImpl<llvm::Metadata *> &elements,
1298 llvm::DICompositeType *RecordTy) {
1299 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1301 if (CXXDecl && CXXDecl->isLambda())
1302 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1304 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1306 // Field number for non-static fields.
1307 unsigned fieldNo = 0;
1309 // Static and non-static members should appear in the same order as
1310 // the corresponding declarations in the source program.
1311 for (const auto *I : record->decls())
1312 if (const auto *V = dyn_cast<VarDecl>(I)) {
1313 if (V->hasAttr<NoDebugAttr>())
1316 // Skip variable template specializations when emitting CodeView. MSVC
1317 // doesn't emit them.
1318 if (CGM.getCodeGenOpts().EmitCodeView &&
1319 isa<VarTemplateSpecializationDecl>(V))
1322 // Reuse the existing static member declaration if one exists
1323 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1324 if (MI != StaticDataMemberCache.end()) {
1325 assert(MI->second &&
1326 "Static data member declaration should still exist");
1327 elements.push_back(MI->second);
1329 auto Field = CreateRecordStaticField(V, RecordTy, record);
1330 elements.push_back(Field);
1332 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1333 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1334 elements, RecordTy, record);
1336 // Bump field number for next field.
1338 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1339 // Debug info for nested types is included in the member list only for
1341 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1342 if (!nestedType->isImplicit() &&
1343 nestedType->getDeclContext() == record)
1344 CollectRecordNestedType(nestedType, elements);
1349 llvm::DISubroutineType *
1350 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1351 llvm::DIFile *Unit) {
1352 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1353 if (Method->isStatic())
1354 return cast_or_null<llvm::DISubroutineType>(
1355 getOrCreateType(QualType(Func, 0), Unit));
1356 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1360 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1361 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1362 // Add "this" pointer.
1363 llvm::DITypeRefArray Args(
1364 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1366 assert(Args.size() && "Invalid number of arguments!");
1368 SmallVector<llvm::Metadata *, 16> Elts;
1370 // First element is always return type. For 'void' functions it is NULL.
1371 Elts.push_back(Args[0]);
1373 // "this" pointer is always first argument.
1374 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1375 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1376 // Create pointer type directly in this case.
1377 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1378 QualType PointeeTy = ThisPtrTy->getPointeeType();
1379 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1380 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1381 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1382 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1383 llvm::DIType *ThisPtrType =
1384 DBuilder.createPointerType(PointeeType, Size, Align);
1385 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1386 // TODO: This and the artificial type below are misleading, the
1387 // types aren't artificial the argument is, but the current
1388 // metadata doesn't represent that.
1389 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1390 Elts.push_back(ThisPtrType);
1392 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1393 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1394 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1395 Elts.push_back(ThisPtrType);
1398 // Copy rest of the arguments.
1399 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1400 Elts.push_back(Args[i]);
1402 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1404 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1405 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1406 Flags |= llvm::DINode::FlagLValueReference;
1407 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1408 Flags |= llvm::DINode::FlagRValueReference;
1410 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1411 getDwarfCC(Func->getCallConv()));
1414 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1415 /// inside a function.
1416 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1417 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1418 return isFunctionLocalClass(NRD);
1419 if (isa<FunctionDecl>(RD->getDeclContext()))
1424 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1425 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1427 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1429 StringRef MethodName = getFunctionName(Method);
1430 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1432 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1433 // make sense to give a single ctor/dtor a linkage name.
1434 StringRef MethodLinkageName;
1435 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1436 // property to use here. It may've been intended to model "is non-external
1437 // type" but misses cases of non-function-local but non-external classes such
1438 // as those in anonymous namespaces as well as the reverse - external types
1439 // that are function local, such as those in (non-local) inline functions.
1440 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1441 MethodLinkageName = CGM.getMangledName(Method);
1443 // Get the location for the method.
1444 llvm::DIFile *MethodDefUnit = nullptr;
1445 unsigned MethodLine = 0;
1446 if (!Method->isImplicit()) {
1447 MethodDefUnit = getOrCreateFile(Method->getLocation());
1448 MethodLine = getLineNumber(Method->getLocation());
1451 // Collect virtual method info.
1452 llvm::DIType *ContainingType = nullptr;
1453 unsigned Virtuality = 0;
1454 unsigned VIndex = 0;
1455 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1456 int ThisAdjustment = 0;
1458 if (Method->isVirtual()) {
1459 if (Method->isPure())
1460 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1462 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1464 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1465 // It doesn't make sense to give a virtual destructor a vtable index,
1466 // since a single destructor has two entries in the vtable.
1467 if (!isa<CXXDestructorDecl>(Method))
1468 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1470 // Emit MS ABI vftable information. There is only one entry for the
1472 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1473 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1474 MethodVFTableLocation ML =
1475 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1478 // CodeView only records the vftable offset in the class that introduces
1479 // the virtual method. This is possible because, unlike Itanium, the MS
1480 // C++ ABI does not include all virtual methods from non-primary bases in
1481 // the vtable for the most derived class. For example, if C inherits from
1482 // A and B, C's primary vftable will not include B's virtual methods.
1483 if (Method->size_overridden_methods() == 0)
1484 Flags |= llvm::DINode::FlagIntroducedVirtual;
1486 // The 'this' adjustment accounts for both the virtual and non-virtual
1487 // portions of the adjustment. Presumably the debugger only uses it when
1488 // it knows the dynamic type of an object.
1489 ThisAdjustment = CGM.getCXXABI()
1490 .getVirtualFunctionPrologueThisAdjustment(GD)
1493 ContainingType = RecordTy;
1496 if (Method->isStatic())
1497 Flags |= llvm::DINode::FlagStaticMember;
1498 if (Method->isImplicit())
1499 Flags |= llvm::DINode::FlagArtificial;
1500 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1501 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1502 if (CXXC->isExplicit())
1503 Flags |= llvm::DINode::FlagExplicit;
1504 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1505 if (CXXC->isExplicit())
1506 Flags |= llvm::DINode::FlagExplicit;
1508 if (Method->hasPrototype())
1509 Flags |= llvm::DINode::FlagPrototyped;
1510 if (Method->getRefQualifier() == RQ_LValue)
1511 Flags |= llvm::DINode::FlagLValueReference;
1512 if (Method->getRefQualifier() == RQ_RValue)
1513 Flags |= llvm::DINode::FlagRValueReference;
1515 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1516 llvm::DISubprogram *SP = DBuilder.createMethod(
1517 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1518 MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
1519 VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
1520 TParamsArray.get());
1522 SPCache[Method->getCanonicalDecl()].reset(SP);
1527 void CGDebugInfo::CollectCXXMemberFunctions(
1528 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1529 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1531 // Since we want more than just the individual member decls if we
1532 // have templated functions iterate over every declaration to gather
1534 for (const auto *I : RD->decls()) {
1535 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1536 // If the member is implicit, don't add it to the member list. This avoids
1537 // the member being added to type units by LLVM, while still allowing it
1538 // to be emitted into the type declaration/reference inside the compile
1540 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1541 // FIXME: Handle Using(Shadow?)Decls here to create
1542 // DW_TAG_imported_declarations inside the class for base decls brought into
1543 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1544 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1546 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1549 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1552 // Reuse the existing member function declaration if it exists.
1553 // It may be associated with the declaration of the type & should be
1554 // reused as we're building the definition.
1556 // This situation can arise in the vtable-based debug info reduction where
1557 // implicit members are emitted in a non-vtable TU.
1558 auto MI = SPCache.find(Method->getCanonicalDecl());
1559 EltTys.push_back(MI == SPCache.end()
1560 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1561 : static_cast<llvm::Metadata *>(MI->second));
1565 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1566 SmallVectorImpl<llvm::Metadata *> &EltTys,
1567 llvm::DIType *RecordTy) {
1568 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1569 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1570 llvm::DINode::FlagZero);
1572 // If we are generating CodeView debug info, we also need to emit records for
1573 // indirect virtual base classes.
1574 if (CGM.getCodeGenOpts().EmitCodeView) {
1575 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1576 llvm::DINode::FlagIndirectVirtualBase);
1580 void CGDebugInfo::CollectCXXBasesAux(
1581 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1582 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1583 const CXXRecordDecl::base_class_const_range &Bases,
1584 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1585 llvm::DINode::DIFlags StartingFlags) {
1586 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1587 for (const auto &BI : Bases) {
1589 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1590 if (!SeenTypes.insert(Base).second)
1592 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1593 llvm::DINode::DIFlags BFlags = StartingFlags;
1594 uint64_t BaseOffset;
1595 uint32_t VBPtrOffset = 0;
1597 if (BI.isVirtual()) {
1598 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1599 // virtual base offset offset is -ve. The code generator emits dwarf
1600 // expression where it expects +ve number.
1601 BaseOffset = 0 - CGM.getItaniumVTableContext()
1602 .getVirtualBaseOffsetOffset(RD, Base)
1605 // In the MS ABI, store the vbtable offset, which is analogous to the
1606 // vbase offset offset in Itanium.
1608 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1609 VBPtrOffset = CGM.getContext()
1610 .getASTRecordLayout(RD)
1614 BFlags |= llvm::DINode::FlagVirtual;
1616 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1617 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1618 // BI->isVirtual() and bits when not.
1620 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1621 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1622 VBPtrOffset, BFlags);
1623 EltTys.push_back(DTy);
1628 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1629 ArrayRef<TemplateArgument> TAList,
1630 llvm::DIFile *Unit) {
1631 SmallVector<llvm::Metadata *, 16> TemplateParams;
1632 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1633 const TemplateArgument &TA = TAList[i];
1636 Name = TPList->getParam(i)->getName();
1637 switch (TA.getKind()) {
1638 case TemplateArgument::Type: {
1639 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1640 TemplateParams.push_back(
1641 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1643 case TemplateArgument::Integral: {
1644 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1645 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1647 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1649 case TemplateArgument::Declaration: {
1650 const ValueDecl *D = TA.getAsDecl();
1651 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1652 llvm::DIType *TTy = getOrCreateType(T, Unit);
1653 llvm::Constant *V = nullptr;
1654 const CXXMethodDecl *MD;
1655 // Variable pointer template parameters have a value that is the address
1657 if (const auto *VD = dyn_cast<VarDecl>(D))
1658 V = CGM.GetAddrOfGlobalVar(VD);
1659 // Member function pointers have special support for building them, though
1660 // this is currently unsupported in LLVM CodeGen.
1661 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1662 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1663 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1664 V = CGM.GetAddrOfFunction(FD);
1665 // Member data pointers have special handling too to compute the fixed
1666 // offset within the object.
1667 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1668 // These five lines (& possibly the above member function pointer
1669 // handling) might be able to be refactored to use similar code in
1670 // CodeGenModule::getMemberPointerConstant
1671 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1673 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1674 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1676 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1678 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1680 case TemplateArgument::NullPtr: {
1681 QualType T = TA.getNullPtrType();
1682 llvm::DIType *TTy = getOrCreateType(T, Unit);
1683 llvm::Constant *V = nullptr;
1684 // Special case member data pointer null values since they're actually -1
1686 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1687 // But treat member function pointers as simple zero integers because
1688 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1689 // CodeGen grows handling for values of non-null member function
1690 // pointers then perhaps we could remove this special case and rely on
1691 // EmitNullMemberPointer for member function pointers.
1692 if (MPT->isMemberDataPointer())
1693 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1695 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1696 TemplateParams.push_back(
1697 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
1699 case TemplateArgument::Template:
1700 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1701 TheCU, Name, nullptr,
1702 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1704 case TemplateArgument::Pack:
1705 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1706 TheCU, Name, nullptr,
1707 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1709 case TemplateArgument::Expression: {
1710 const Expr *E = TA.getAsExpr();
1711 QualType T = E->getType();
1713 T = CGM.getContext().getLValueReferenceType(T);
1714 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1715 assert(V && "Expression in template argument isn't constant");
1716 llvm::DIType *TTy = getOrCreateType(T, Unit);
1717 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1718 TheCU, Name, TTy, V->stripPointerCasts()));
1720 // And the following should never occur:
1721 case TemplateArgument::TemplateExpansion:
1722 case TemplateArgument::Null:
1724 "These argument types shouldn't exist in concrete types");
1727 return DBuilder.getOrCreateArray(TemplateParams);
1731 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1732 llvm::DIFile *Unit) {
1733 if (FD->getTemplatedKind() ==
1734 FunctionDecl::TK_FunctionTemplateSpecialization) {
1735 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1737 ->getTemplateParameters();
1738 return CollectTemplateParams(
1739 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1741 return llvm::DINodeArray();
1744 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1745 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1746 // Always get the full list of parameters, not just the ones from
1747 // the specialization.
1748 TemplateParameterList *TPList =
1749 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1750 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1751 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1754 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1756 return VTablePtrType;
1758 ASTContext &Context = CGM.getContext();
1761 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1762 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1763 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1764 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1765 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1766 Optional<unsigned> DWARFAddressSpace =
1767 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1769 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1770 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1771 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1772 return VTablePtrType;
1775 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1776 // Copy the gdb compatible name on the side and use its reference.
1777 return internString("_vptr$", RD->getNameAsString());
1780 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1781 SmallVectorImpl<llvm::Metadata *> &EltTys,
1782 llvm::DICompositeType *RecordTy) {
1783 // If this class is not dynamic then there is not any vtable info to collect.
1784 if (!RD->isDynamicClass())
1787 // Don't emit any vtable shape or vptr info if this class doesn't have an
1788 // extendable vfptr. This can happen if the class doesn't have virtual
1789 // methods, or in the MS ABI if those virtual methods only come from virtually
1791 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1792 if (!RL.hasExtendableVFPtr())
1795 // CodeView needs to know how large the vtable of every dynamic class is, so
1796 // emit a special named pointer type into the element list. The vptr type
1797 // points to this type as well.
1798 llvm::DIType *VPtrTy = nullptr;
1799 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1800 CGM.getTarget().getCXXABI().isMicrosoft();
1801 if (NeedVTableShape) {
1803 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1804 const VTableLayout &VFTLayout =
1805 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1806 unsigned VSlotCount =
1807 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
1808 unsigned VTableWidth = PtrWidth * VSlotCount;
1809 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1810 Optional<unsigned> DWARFAddressSpace =
1811 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1813 // Create a very wide void* type and insert it directly in the element list.
1814 llvm::DIType *VTableType = DBuilder.createPointerType(
1815 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1816 EltTys.push_back(VTableType);
1818 // The vptr is a pointer to this special vtable type.
1819 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1822 // If there is a primary base then the artificial vptr member lives there.
1823 if (RL.getPrimaryBase())
1827 VPtrTy = getOrCreateVTablePtrType(Unit);
1829 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1830 llvm::DIType *VPtrMember =
1831 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1832 llvm::DINode::FlagArtificial, VPtrTy);
1833 EltTys.push_back(VPtrMember);
1836 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1837 SourceLocation Loc) {
1838 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1839 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1843 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1844 SourceLocation Loc) {
1845 return getOrCreateStandaloneType(D, Loc);
1848 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1849 SourceLocation Loc) {
1850 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1851 assert(!D.isNull() && "null type");
1852 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1853 assert(T && "could not create debug info for type");
1855 RetainedTypes.push_back(D.getAsOpaquePtr());
1859 void CGDebugInfo::completeType(const EnumDecl *ED) {
1860 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1862 QualType Ty = CGM.getContext().getEnumType(ED);
1863 void *TyPtr = Ty.getAsOpaquePtr();
1864 auto I = TypeCache.find(TyPtr);
1865 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1867 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1868 assert(!Res->isForwardDecl());
1869 TypeCache[TyPtr].reset(Res);
1872 void CGDebugInfo::completeType(const RecordDecl *RD) {
1873 if (DebugKind > codegenoptions::LimitedDebugInfo ||
1874 !CGM.getLangOpts().CPlusPlus)
1875 completeRequiredType(RD);
1878 /// Return true if the class or any of its methods are marked dllimport.
1879 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1880 if (RD->hasAttr<DLLImportAttr>())
1882 for (const CXXMethodDecl *MD : RD->methods())
1883 if (MD->hasAttr<DLLImportAttr>())
1888 /// Does a type definition exist in an imported clang module?
1889 static bool isDefinedInClangModule(const RecordDecl *RD) {
1890 // Only definitions that where imported from an AST file come from a module.
1891 if (!RD || !RD->isFromASTFile())
1893 // Anonymous entities cannot be addressed. Treat them as not from module.
1894 if (!RD->isExternallyVisible() && RD->getName().empty())
1896 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1897 if (!CXXDecl->isCompleteDefinition())
1899 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
1900 if (TemplateKind != TSK_Undeclared) {
1901 // This is a template, check the origin of the first member.
1902 if (CXXDecl->field_begin() == CXXDecl->field_end())
1903 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
1904 if (!CXXDecl->field_begin()->isFromASTFile())
1911 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1912 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1913 if (CXXRD->isDynamicClass() &&
1914 CGM.getVTableLinkage(CXXRD) ==
1915 llvm::GlobalValue::AvailableExternallyLinkage &&
1916 !isClassOrMethodDLLImport(CXXRD))
1919 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1925 void CGDebugInfo::completeClass(const RecordDecl *RD) {
1926 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1928 QualType Ty = CGM.getContext().getRecordType(RD);
1929 void *TyPtr = Ty.getAsOpaquePtr();
1930 auto I = TypeCache.find(TyPtr);
1931 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1933 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1934 assert(!Res->isForwardDecl());
1935 TypeCache[TyPtr].reset(Res);
1938 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1939 CXXRecordDecl::method_iterator End) {
1940 for (CXXMethodDecl *MD : llvm::make_range(I, End))
1941 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
1942 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1943 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
1948 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
1949 bool DebugTypeExtRefs, const RecordDecl *RD,
1950 const LangOptions &LangOpts) {
1951 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1954 if (auto *ES = RD->getASTContext().getExternalSource())
1955 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
1958 if (DebugKind > codegenoptions::LimitedDebugInfo)
1961 if (!LangOpts.CPlusPlus)
1964 if (!RD->isCompleteDefinitionRequired())
1967 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1972 // Only emit complete debug info for a dynamic class when its vtable is
1973 // emitted. However, Microsoft debuggers don't resolve type information
1974 // across DLL boundaries, so skip this optimization if the class or any of its
1975 // methods are marked dllimport. This isn't a complete solution, since objects
1976 // without any dllimport methods can be used in one DLL and constructed in
1977 // another, but it is the current behavior of LimitedDebugInfo.
1978 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
1979 !isClassOrMethodDLLImport(CXXDecl))
1982 TemplateSpecializationKind Spec = TSK_Undeclared;
1983 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1984 Spec = SD->getSpecializationKind();
1986 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1987 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1988 CXXDecl->method_end()))
1994 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1995 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
1998 QualType Ty = CGM.getContext().getRecordType(RD);
1999 llvm::DIType *T = getTypeOrNull(Ty);
2000 if (T && T->isForwardDecl())
2001 completeClassData(RD);
2004 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2005 RecordDecl *RD = Ty->getDecl();
2006 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2007 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2008 CGM.getLangOpts())) {
2010 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2014 return CreateTypeDefinition(Ty);
2017 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2018 RecordDecl *RD = Ty->getDecl();
2020 // Get overall information about the record type for the debug info.
2021 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2023 // Records and classes and unions can all be recursive. To handle them, we
2024 // first generate a debug descriptor for the struct as a forward declaration.
2025 // Then (if it is a definition) we go through and get debug info for all of
2026 // its members. Finally, we create a descriptor for the complete type (which
2027 // may refer to the forward decl if the struct is recursive) and replace all
2028 // uses of the forward declaration with the final definition.
2029 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2031 const RecordDecl *D = RD->getDefinition();
2032 if (!D || !D->isCompleteDefinition())
2035 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2036 CollectContainingType(CXXDecl, FwdDecl);
2038 // Push the struct on region stack.
2039 LexicalBlockStack.emplace_back(&*FwdDecl);
2040 RegionMap[Ty->getDecl()].reset(FwdDecl);
2042 // Convert all the elements.
2043 SmallVector<llvm::Metadata *, 16> EltTys;
2044 // what about nested types?
2046 // Note: The split of CXXDecl information here is intentional, the
2047 // gdb tests will depend on a certain ordering at printout. The debug
2048 // information offsets are still correct if we merge them all together
2050 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2052 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2053 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2056 // Collect data fields (including static variables and any initializers).
2057 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2059 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2061 LexicalBlockStack.pop_back();
2062 RegionMap.erase(Ty->getDecl());
2064 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2065 DBuilder.replaceArrays(FwdDecl, Elements);
2067 if (FwdDecl->isTemporary())
2069 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2071 RegionMap[Ty->getDecl()].reset(FwdDecl);
2075 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2076 llvm::DIFile *Unit) {
2077 // Ignore protocols.
2078 return getOrCreateType(Ty->getBaseType(), Unit);
2081 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2082 llvm::DIFile *Unit) {
2083 // Ignore protocols.
2084 SourceLocation Loc = Ty->getDecl()->getLocation();
2086 // Use Typedefs to represent ObjCTypeParamType.
2087 return DBuilder.createTypedef(
2088 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2089 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2090 getDeclContextDescriptor(Ty->getDecl()));
2093 /// \return true if Getter has the default name for the property PD.
2094 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2095 const ObjCMethodDecl *Getter) {
2100 assert(Getter->getDeclName().isObjCZeroArgSelector());
2101 return PD->getName() ==
2102 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2105 /// \return true if Setter has the default name for the property PD.
2106 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2107 const ObjCMethodDecl *Setter) {
2112 assert(Setter->getDeclName().isObjCOneArgSelector());
2113 return SelectorTable::constructSetterName(PD->getName()) ==
2114 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2117 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2118 llvm::DIFile *Unit) {
2119 ObjCInterfaceDecl *ID = Ty->getDecl();
2123 // Return a forward declaration if this type was imported from a clang module,
2124 // and this is not the compile unit with the implementation of the type (which
2125 // may contain hidden ivars).
2126 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2127 !ID->getImplementation())
2128 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2130 getDeclContextDescriptor(ID), Unit, 0);
2132 // Get overall information about the record type for the debug info.
2133 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2134 unsigned Line = getLineNumber(ID->getLocation());
2136 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2138 // If this is just a forward declaration return a special forward-declaration
2139 // debug type since we won't be able to lay out the entire type.
2140 ObjCInterfaceDecl *Def = ID->getDefinition();
2141 if (!Def || !Def->getImplementation()) {
2142 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2143 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2144 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2145 DefUnit, Line, RuntimeLang);
2146 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2150 return CreateTypeDefinition(Ty, Unit);
2154 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2155 bool CreateSkeletonCU) {
2156 // Use the Module pointer as the key into the cache. This is a
2157 // nullptr if the "Module" is a PCH, which is safe because we don't
2158 // support chained PCH debug info, so there can only be a single PCH.
2159 const Module *M = Mod.getModuleOrNull();
2160 auto ModRef = ModuleCache.find(M);
2161 if (ModRef != ModuleCache.end())
2162 return cast<llvm::DIModule>(ModRef->second);
2164 // Macro definitions that were defined with "-D" on the command line.
2165 SmallString<128> ConfigMacros;
2167 llvm::raw_svector_ostream OS(ConfigMacros);
2168 const auto &PPOpts = CGM.getPreprocessorOpts();
2170 // Translate the macro definitions back into a command line.
2171 for (auto &M : PPOpts.Macros) {
2174 const std::string &Macro = M.first;
2175 bool Undef = M.second;
2176 OS << "\"-" << (Undef ? 'U' : 'D');
2177 for (char c : Macro)
2192 bool IsRootModule = M ? !M->Parent : true;
2193 if (CreateSkeletonCU && IsRootModule) {
2194 // PCH files don't have a signature field in the control block,
2195 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2196 // We use the lower 64 bits for debug info.
2197 uint64_t Signature =
2199 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2201 llvm::DIBuilder DIB(CGM.getModule());
2202 DIB.createCompileUnit(TheCU->getSourceLanguage(),
2203 // TODO: Support "Source" from external AST providers?
2204 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2205 TheCU->getProducer(), true, StringRef(), 0,
2206 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2210 llvm::DIModule *Parent =
2211 IsRootModule ? nullptr
2212 : getOrCreateModuleRef(
2213 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2215 llvm::DIModule *DIMod =
2216 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2217 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2218 ModuleCache[M].reset(DIMod);
2222 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2223 llvm::DIFile *Unit) {
2224 ObjCInterfaceDecl *ID = Ty->getDecl();
2225 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2226 unsigned Line = getLineNumber(ID->getLocation());
2227 unsigned RuntimeLang = TheCU->getSourceLanguage();
2229 // Bit size, align and offset of the type.
2230 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2231 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2233 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2234 if (ID->getImplementation())
2235 Flags |= llvm::DINode::FlagObjcClassComplete;
2237 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2238 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2239 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2240 nullptr, llvm::DINodeArray(), RuntimeLang);
2242 QualType QTy(Ty, 0);
2243 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2245 // Push the struct on region stack.
2246 LexicalBlockStack.emplace_back(RealDecl);
2247 RegionMap[Ty->getDecl()].reset(RealDecl);
2249 // Convert all the elements.
2250 SmallVector<llvm::Metadata *, 16> EltTys;
2252 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2254 llvm::DIType *SClassTy =
2255 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2259 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2260 llvm::DINode::FlagZero);
2261 EltTys.push_back(InhTag);
2264 // Create entries for all of the properties.
2265 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2266 SourceLocation Loc = PD->getLocation();
2267 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2268 unsigned PLine = getLineNumber(Loc);
2269 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2270 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2271 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2272 PD->getName(), PUnit, PLine,
2273 hasDefaultGetterName(PD, Getter) ? ""
2274 : getSelectorName(PD->getGetterName()),
2275 hasDefaultSetterName(PD, Setter) ? ""
2276 : getSelectorName(PD->getSetterName()),
2277 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2278 EltTys.push_back(PropertyNode);
2281 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2282 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2283 for (auto *PD : ClassExt->properties()) {
2284 PropertySet.insert(PD->getIdentifier());
2287 for (const auto *PD : ID->properties()) {
2288 // Don't emit duplicate metadata for properties that were already in a
2290 if (!PropertySet.insert(PD->getIdentifier()).second)
2296 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2297 unsigned FieldNo = 0;
2298 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2299 Field = Field->getNextIvar(), ++FieldNo) {
2300 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2304 StringRef FieldName = Field->getName();
2306 // Ignore unnamed fields.
2307 if (FieldName.empty())
2310 // Get the location for the field.
2311 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2312 unsigned FieldLine = getLineNumber(Field->getLocation());
2313 QualType FType = Field->getType();
2314 uint64_t FieldSize = 0;
2315 uint32_t FieldAlign = 0;
2317 if (!FType->isIncompleteArrayType()) {
2319 // Bit size, align and offset of the type.
2320 FieldSize = Field->isBitField()
2321 ? Field->getBitWidthValue(CGM.getContext())
2322 : CGM.getContext().getTypeSize(FType);
2323 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2326 uint64_t FieldOffset;
2327 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2328 // We don't know the runtime offset of an ivar if we're using the
2329 // non-fragile ABI. For bitfields, use the bit offset into the first
2330 // byte of storage of the bitfield. For other fields, use zero.
2331 if (Field->isBitField()) {
2333 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2334 FieldOffset %= CGM.getContext().getCharWidth();
2339 FieldOffset = RL.getFieldOffset(FieldNo);
2342 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2343 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2344 Flags = llvm::DINode::FlagProtected;
2345 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2346 Flags = llvm::DINode::FlagPrivate;
2347 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2348 Flags = llvm::DINode::FlagPublic;
2350 llvm::MDNode *PropertyNode = nullptr;
2351 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2352 if (ObjCPropertyImplDecl *PImpD =
2353 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2354 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2355 SourceLocation Loc = PD->getLocation();
2356 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2357 unsigned PLine = getLineNumber(Loc);
2358 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2359 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2360 PropertyNode = DBuilder.createObjCProperty(
2361 PD->getName(), PUnit, PLine,
2362 hasDefaultGetterName(PD, Getter)
2364 : getSelectorName(PD->getGetterName()),
2365 hasDefaultSetterName(PD, Setter)
2367 : getSelectorName(PD->getSetterName()),
2368 PD->getPropertyAttributes(),
2369 getOrCreateType(PD->getType(), PUnit));
2373 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2374 FieldSize, FieldAlign, FieldOffset, Flags,
2375 FieldTy, PropertyNode);
2376 EltTys.push_back(FieldTy);
2379 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2380 DBuilder.replaceArrays(RealDecl, Elements);
2382 LexicalBlockStack.pop_back();
2386 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2387 llvm::DIFile *Unit) {
2388 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2389 int64_t Count = Ty->getNumElements();
2391 llvm::Metadata *Subscript;
2392 QualType QTy(Ty, 0);
2393 auto SizeExpr = SizeExprCache.find(QTy);
2394 if (SizeExpr != SizeExprCache.end())
2395 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2397 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
2398 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2400 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2401 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2403 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2406 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2410 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2411 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2413 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2415 } else if (Ty->isIncompleteArrayType()) {
2417 if (Ty->getElementType()->isIncompleteType())
2420 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2421 } else if (Ty->isIncompleteType()) {
2425 // Size and align of the whole array, not the element type.
2426 Size = CGM.getContext().getTypeSize(Ty);
2427 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2430 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2431 // interior arrays, do we care? Why aren't nested arrays represented the
2432 // obvious/recursive way?
2433 SmallVector<llvm::Metadata *, 8> Subscripts;
2434 QualType EltTy(Ty, 0);
2435 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2436 // If the number of elements is known, then count is that number. Otherwise,
2437 // it's -1. This allows us to represent a subrange with an array of 0
2438 // elements, like this:
2443 int64_t Count = -1; // Count == -1 is an unbounded array.
2444 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2445 Count = CAT->getSize().getZExtValue();
2446 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2447 if (Expr *Size = VAT->getSizeExpr()) {
2449 if (Size->EvaluateAsInt(V, CGM.getContext()))
2450 Count = V.getExtValue();
2454 auto SizeNode = SizeExprCache.find(EltTy);
2455 if (SizeNode != SizeExprCache.end())
2456 Subscripts.push_back(
2457 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2459 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2460 EltTy = Ty->getElementType();
2463 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2465 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2469 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2470 llvm::DIFile *Unit) {
2471 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2472 Ty->getPointeeType(), Unit);
2475 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2476 llvm::DIFile *Unit) {
2477 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2478 Ty->getPointeeType(), Unit);
2481 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2483 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2486 if (!Ty->isIncompleteType()) {
2487 Size = CGM.getContext().getTypeSize(Ty);
2489 // Set the MS inheritance model. There is no flag for the unspecified model.
2490 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2491 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2492 case MSInheritanceAttr::Keyword_single_inheritance:
2493 Flags |= llvm::DINode::FlagSingleInheritance;
2495 case MSInheritanceAttr::Keyword_multiple_inheritance:
2496 Flags |= llvm::DINode::FlagMultipleInheritance;
2498 case MSInheritanceAttr::Keyword_virtual_inheritance:
2499 Flags |= llvm::DINode::FlagVirtualInheritance;
2501 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2507 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2508 if (Ty->isMemberDataPointerType())
2509 return DBuilder.createMemberPointerType(
2510 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2513 const FunctionProtoType *FPT =
2514 Ty->getPointeeType()->getAs<FunctionProtoType>();
2515 return DBuilder.createMemberPointerType(
2516 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2517 Ty->getClass(), FPT->getTypeQuals())),
2519 ClassType, Size, /*Align=*/0, Flags);
2522 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2523 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2524 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2527 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2528 return getOrCreateType(Ty->getElementType(), U);
2531 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2532 const EnumDecl *ED = Ty->getDecl();
2536 if (!ED->getTypeForDecl()->isIncompleteType()) {
2537 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2538 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2541 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2543 bool isImportedFromModule =
2544 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2546 // If this is just a forward declaration, construct an appropriately
2547 // marked node and just return it.
2548 if (isImportedFromModule || !ED->getDefinition()) {
2549 // Note that it is possible for enums to be created as part of
2550 // their own declcontext. In this case a FwdDecl will be created
2551 // twice. This doesn't cause a problem because both FwdDecls are
2552 // entered into the ReplaceMap: finalize() will replace the first
2553 // FwdDecl with the second and then replace the second with
2555 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2556 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2557 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2558 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2560 unsigned Line = getLineNumber(ED->getLocation());
2561 StringRef EDName = ED->getName();
2562 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2563 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2564 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2566 ReplaceMap.emplace_back(
2567 std::piecewise_construct, std::make_tuple(Ty),
2568 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2572 return CreateTypeDefinition(Ty);
2575 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2576 const EnumDecl *ED = Ty->getDecl();
2579 if (!ED->getTypeForDecl()->isIncompleteType()) {
2580 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2581 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2584 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2586 // Create elements for each enumerator.
2587 SmallVector<llvm::Metadata *, 16> Enumerators;
2588 ED = ED->getDefinition();
2589 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2590 for (const auto *Enum : ED->enumerators()) {
2591 const auto &InitVal = Enum->getInitVal();
2592 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2593 Enumerators.push_back(
2594 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
2597 // Return a CompositeType for the enum itself.
2598 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2600 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2601 unsigned Line = getLineNumber(ED->getLocation());
2602 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2603 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
2604 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2605 Line, Size, Align, EltArray, ClassTy,
2606 Identifier, ED->isFixed());
2609 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2610 unsigned MType, SourceLocation LineLoc,
2611 StringRef Name, StringRef Value) {
2612 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2613 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2616 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2617 SourceLocation LineLoc,
2618 SourceLocation FileLoc) {
2619 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2620 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2621 return DBuilder.createTempMacroFile(Parent, Line, FName);
2624 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2627 Qualifiers InnerQuals = T.getLocalQualifiers();
2628 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2629 // that is already there.
2630 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2631 Quals += InnerQuals;
2633 switch (T->getTypeClass()) {
2635 return C.getQualifiedType(T.getTypePtr(), Quals);
2636 case Type::TemplateSpecialization: {
2637 const auto *Spec = cast<TemplateSpecializationType>(T);
2638 if (Spec->isTypeAlias())
2639 return C.getQualifiedType(T.getTypePtr(), Quals);
2640 T = Spec->desugar();
2643 case Type::TypeOfExpr:
2644 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2647 T = cast<TypeOfType>(T)->getUnderlyingType();
2649 case Type::Decltype:
2650 T = cast<DecltypeType>(T)->getUnderlyingType();
2652 case Type::UnaryTransform:
2653 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2655 case Type::Attributed:
2656 T = cast<AttributedType>(T)->getEquivalentType();
2658 case Type::Elaborated:
2659 T = cast<ElaboratedType>(T)->getNamedType();
2662 T = cast<ParenType>(T)->getInnerType();
2664 case Type::SubstTemplateTypeParm:
2665 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2668 case Type::DeducedTemplateSpecialization: {
2669 QualType DT = cast<DeducedType>(T)->getDeducedType();
2670 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2674 case Type::Adjusted:
2676 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2677 T = cast<AdjustedType>(T)->getAdjustedType();
2681 assert(T != LastT && "Type unwrapping failed to unwrap!");
2686 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2688 // Unwrap the type as needed for debug information.
2689 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2691 auto It = TypeCache.find(Ty.getAsOpaquePtr());
2692 if (It != TypeCache.end()) {
2693 // Verify that the debug info still exists.
2694 if (llvm::Metadata *V = It->second)
2695 return cast<llvm::DIType>(V);
2701 void CGDebugInfo::completeTemplateDefinition(
2702 const ClassTemplateSpecializationDecl &SD) {
2703 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2705 completeUnusedClass(SD);
2708 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2709 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2712 completeClassData(&D);
2713 // In case this type has no member function definitions being emitted, ensure
2715 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2718 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2722 // Unwrap the type as needed for debug information.
2723 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2725 if (auto *T = getTypeOrNull(Ty))
2728 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2729 void *TyPtr = Ty.getAsOpaquePtr();
2731 // And update the type cache.
2732 TypeCache[TyPtr].reset(Res);
2737 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2738 // A forward declaration inside a module header does not belong to the module.
2739 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2741 if (DebugTypeExtRefs && D->isFromASTFile()) {
2742 // Record a reference to an imported clang module or precompiled header.
2743 auto *Reader = CGM.getContext().getExternalSource();
2744 auto Idx = D->getOwningModuleID();
2745 auto Info = Reader->getSourceDescriptor(Idx);
2747 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2748 } else if (ClangModuleMap) {
2749 // We are building a clang module or a precompiled header.
2751 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2752 // and it wouldn't be necessary to specify the parent scope
2753 // because the type is already unique by definition (it would look
2754 // like the output of -fno-standalone-debug). On the other hand,
2755 // the parent scope helps a consumer to quickly locate the object
2756 // file where the type's definition is located, so it might be
2757 // best to make this behavior a command line or debugger tuning
2759 if (Module *M = D->getOwningModule()) {
2760 // This is a (sub-)module.
2761 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2762 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2764 // This the precompiled header being built.
2765 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2772 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2773 // Handle qualifiers, which recursively handles what they refer to.
2774 if (Ty.hasLocalQualifiers())
2775 return CreateQualifiedType(Ty, Unit);
2777 // Work out details of type.
2778 switch (Ty->getTypeClass()) {
2779 #define TYPE(Class, Base)
2780 #define ABSTRACT_TYPE(Class, Base)
2781 #define NON_CANONICAL_TYPE(Class, Base)
2782 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2783 #include "clang/AST/TypeNodes.def"
2784 llvm_unreachable("Dependent types cannot show up in debug information");
2786 case Type::ExtVector:
2788 return CreateType(cast<VectorType>(Ty), Unit);
2789 case Type::ObjCObjectPointer:
2790 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2791 case Type::ObjCObject:
2792 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2793 case Type::ObjCTypeParam:
2794 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
2795 case Type::ObjCInterface:
2796 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2798 return CreateType(cast<BuiltinType>(Ty));
2800 return CreateType(cast<ComplexType>(Ty));
2802 return CreateType(cast<PointerType>(Ty), Unit);
2803 case Type::BlockPointer:
2804 return CreateType(cast<BlockPointerType>(Ty), Unit);
2806 return CreateType(cast<TypedefType>(Ty), Unit);
2808 return CreateType(cast<RecordType>(Ty));
2810 return CreateEnumType(cast<EnumType>(Ty));
2811 case Type::FunctionProto:
2812 case Type::FunctionNoProto:
2813 return CreateType(cast<FunctionType>(Ty), Unit);
2814 case Type::ConstantArray:
2815 case Type::VariableArray:
2816 case Type::IncompleteArray:
2817 return CreateType(cast<ArrayType>(Ty), Unit);
2819 case Type::LValueReference:
2820 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2821 case Type::RValueReference:
2822 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2824 case Type::MemberPointer:
2825 return CreateType(cast<MemberPointerType>(Ty), Unit);
2828 return CreateType(cast<AtomicType>(Ty), Unit);
2831 return CreateType(cast<PipeType>(Ty), Unit);
2833 case Type::TemplateSpecialization:
2834 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2837 case Type::Attributed:
2838 case Type::Adjusted:
2840 case Type::DeducedTemplateSpecialization:
2841 case Type::Elaborated:
2843 case Type::SubstTemplateTypeParm:
2844 case Type::TypeOfExpr:
2846 case Type::Decltype:
2847 case Type::UnaryTransform:
2848 case Type::PackExpansion:
2852 llvm_unreachable("type should have been unwrapped!");
2855 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2856 llvm::DIFile *Unit) {
2857 QualType QTy(Ty, 0);
2859 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2861 // We may have cached a forward decl when we could have created
2862 // a non-forward decl. Go ahead and create a non-forward decl
2864 if (T && !T->isForwardDecl())
2867 // Otherwise create the type.
2868 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2870 // Propagate members from the declaration to the definition
2871 // CreateType(const RecordType*) will overwrite this with the members in the
2872 // correct order if the full type is needed.
2873 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2875 // And update the type cache.
2876 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2880 // TODO: Currently used for context chains when limiting debug info.
2881 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2882 RecordDecl *RD = Ty->getDecl();
2884 // Get overall information about the record type for the debug info.
2885 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2886 unsigned Line = getLineNumber(RD->getLocation());
2887 StringRef RDName = getClassName(RD);
2889 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2891 // If we ended up creating the type during the context chain construction,
2892 // just return that.
2893 auto *T = cast_or_null<llvm::DICompositeType>(
2894 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2895 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2898 // If this is just a forward or incomplete declaration, construct an
2899 // appropriately marked node and just return it.
2900 const RecordDecl *D = RD->getDefinition();
2901 if (!D || !D->isCompleteDefinition())
2902 return getOrCreateRecordFwdDecl(Ty, RDContext);
2904 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2905 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
2907 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2909 // Explicitly record the calling convention for C++ records.
2910 auto Flags = llvm::DINode::FlagZero;
2911 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2912 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
2913 Flags |= llvm::DINode::FlagTypePassByReference;
2915 Flags |= llvm::DINode::FlagTypePassByValue;
2917 // Record if a C++ record is trivial type.
2918 if (CXXRD->isTrivial())
2919 Flags |= llvm::DINode::FlagTrivial;
2922 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2923 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
2926 // Elements of composite types usually have back to the type, creating
2927 // uniquing cycles. Distinct nodes are more efficient.
2928 switch (RealDecl->getTag()) {
2930 llvm_unreachable("invalid composite type tag");
2932 case llvm::dwarf::DW_TAG_array_type:
2933 case llvm::dwarf::DW_TAG_enumeration_type:
2934 // Array elements and most enumeration elements don't have back references,
2935 // so they don't tend to be involved in uniquing cycles and there is some
2936 // chance of merging them when linking together two modules. Only make
2937 // them distinct if they are ODR-uniqued.
2938 if (Identifier.empty())
2942 case llvm::dwarf::DW_TAG_structure_type:
2943 case llvm::dwarf::DW_TAG_union_type:
2944 case llvm::dwarf::DW_TAG_class_type:
2945 // Immediately resolve to a distinct node.
2947 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
2951 RegionMap[Ty->getDecl()].reset(RealDecl);
2952 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2954 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2955 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2956 CollectCXXTemplateParams(TSpecial, DefUnit));
2960 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2961 llvm::DICompositeType *RealDecl) {
2962 // A class's primary base or the class itself contains the vtable.
2963 llvm::DICompositeType *ContainingType = nullptr;
2964 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2965 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2966 // Seek non-virtual primary base root.
2968 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2969 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2970 if (PBT && !BRL.isPrimaryBaseVirtual())
2975 ContainingType = cast<llvm::DICompositeType>(
2976 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2977 getOrCreateFile(RD->getLocation())));
2978 } else if (RD->isDynamicClass())
2979 ContainingType = RealDecl;
2981 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2984 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2985 StringRef Name, uint64_t *Offset) {
2986 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2987 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2988 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2990 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
2991 *Offset, llvm::DINode::FlagZero, FieldTy);
2992 *Offset += FieldSize;
2996 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2998 StringRef &LinkageName,
2999 llvm::DIScope *&FDContext,
3000 llvm::DINodeArray &TParamsArray,
3001 llvm::DINode::DIFlags &Flags) {
3002 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3003 Name = getFunctionName(FD);
3004 // Use mangled name as linkage name for C/C++ functions.
3005 if (FD->hasPrototype()) {
3006 LinkageName = CGM.getMangledName(GD);
3007 Flags |= llvm::DINode::FlagPrototyped;
3009 // No need to replicate the linkage name if it isn't different from the
3010 // subprogram name, no need to have it at all unless coverage is enabled or
3011 // debug is set to more than just line tables or extra debug info is needed.
3012 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3013 !CGM.getCodeGenOpts().EmitGcovNotes &&
3014 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3015 DebugKind <= codegenoptions::DebugLineTablesOnly))
3016 LinkageName = StringRef();
3018 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
3019 if (const NamespaceDecl *NSDecl =
3020 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3021 FDContext = getOrCreateNamespace(NSDecl);
3022 else if (const RecordDecl *RDecl =
3023 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3024 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3025 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3027 // Check if it is a noreturn-marked function
3028 if (FD->isNoReturn())
3029 Flags |= llvm::DINode::FlagNoReturn;
3030 // Collect template parameters.
3031 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3035 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3036 unsigned &LineNo, QualType &T,
3037 StringRef &Name, StringRef &LinkageName,
3038 llvm::DIScope *&VDContext) {
3039 Unit = getOrCreateFile(VD->getLocation());
3040 LineNo = getLineNumber(VD->getLocation());
3042 setLocation(VD->getLocation());
3045 if (T->isIncompleteArrayType()) {
3046 // CodeGen turns int[] into int[1] so we'll do the same here.
3047 llvm::APInt ConstVal(32, 1);
3048 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3050 T = CGM.getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal,
3054 Name = VD->getName();
3055 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3056 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3057 LinkageName = CGM.getMangledName(VD);
3058 if (LinkageName == Name)
3059 LinkageName = StringRef();
3061 // Since we emit declarations (DW_AT_members) for static members, place the
3062 // definition of those static members in the namespace they were declared in
3063 // in the source code (the lexical decl context).
3064 // FIXME: Generalize this for even non-member global variables where the
3065 // declaration and definition may have different lexical decl contexts, once
3066 // we have support for emitting declarations of (non-member) global variables.
3067 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3068 : VD->getDeclContext();
3069 // When a record type contains an in-line initialization of a static data
3070 // member, and the record type is marked as __declspec(dllexport), an implicit
3071 // definition of the member will be created in the record context. DWARF
3072 // doesn't seem to have a nice way to describe this in a form that consumers
3073 // are likely to understand, so fake the "normal" situation of a definition
3074 // outside the class by putting it in the global scope.
3076 DC = CGM.getContext().getTranslationUnitDecl();
3078 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3079 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3082 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3084 llvm::DINodeArray TParamsArray;
3085 StringRef Name, LinkageName;
3086 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3087 SourceLocation Loc = GD.getDecl()->getLocation();
3088 llvm::DIFile *Unit = getOrCreateFile(Loc);
3089 llvm::DIScope *DContext = Unit;
3090 unsigned Line = getLineNumber(Loc);
3091 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3093 auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
3095 // Build function type.
3096 SmallVector<QualType, 16> ArgTypes;
3098 for (const ParmVarDecl *Parm : FD->parameters())
3099 ArgTypes.push_back(Parm->getType());
3100 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3101 QualType FnType = CGM.getContext().getFunctionType(
3102 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3104 return DBuilder.createFunction(
3105 DContext, Name, LinkageName, Unit, Line,
3106 getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
3107 !FD->isExternallyVisible(),
3108 /* isDefinition = */ true, 0, Flags, CGM.getLangOpts().Optimize,
3109 TParamsArray.get(), getFunctionDeclaration(FD));
3112 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3113 DContext, Name, LinkageName, Unit, Line,
3114 getOrCreateFunctionType(GD.getDecl(), FnType, Unit),
3115 !FD->isExternallyVisible(),
3116 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
3117 TParamsArray.get(), getFunctionDeclaration(FD));
3118 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3119 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3120 std::make_tuple(CanonDecl),
3121 std::make_tuple(SP));
3125 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3126 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3129 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3130 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3133 llvm::DIGlobalVariable *
3134 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3136 StringRef Name, LinkageName;
3137 SourceLocation Loc = VD->getLocation();
3138 llvm::DIFile *Unit = getOrCreateFile(Loc);
3139 llvm::DIScope *DContext = Unit;
3140 unsigned Line = getLineNumber(Loc);
3142 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
3143 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3144 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3145 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3146 !VD->isExternallyVisible(), nullptr, Align);
3147 FwdDeclReplaceMap.emplace_back(
3148 std::piecewise_construct,
3149 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3150 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3154 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3155 // We only need a declaration (not a definition) of the type - so use whatever
3156 // we would otherwise do to get a type for a pointee. (forward declarations in
3157 // limited debug info, full definitions (if the type definition is available)
3158 // in unlimited debug info)
3159 if (const auto *TD = dyn_cast<TypeDecl>(D))
3160 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3161 getOrCreateFile(TD->getLocation()));
3162 auto I = DeclCache.find(D->getCanonicalDecl());
3164 if (I != DeclCache.end()) {
3166 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3167 return GVE->getVariable();
3168 return dyn_cast_or_null<llvm::DINode>(N);
3171 // No definition for now. Emit a forward definition that might be
3172 // merged with a potential upcoming definition.
3173 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3174 return getFunctionForwardDeclaration(FD);
3175 else if (const auto *VD = dyn_cast<VarDecl>(D))
3176 return getGlobalVariableForwardDeclaration(VD);
3181 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3182 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3185 const auto *FD = dyn_cast<FunctionDecl>(D);
3190 auto *S = getDeclContextDescriptor(D);
3192 auto MI = SPCache.find(FD->getCanonicalDecl());
3193 if (MI == SPCache.end()) {
3194 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3195 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3196 cast<llvm::DICompositeType>(S));
3199 if (MI != SPCache.end()) {
3200 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3201 if (SP && !SP->isDefinition())
3205 for (auto NextFD : FD->redecls()) {
3206 auto MI = SPCache.find(NextFD->getCanonicalDecl());
3207 if (MI != SPCache.end()) {
3208 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3209 if (SP && !SP->isDefinition())
3216 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3217 // implicit parameter "this".
3218 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3221 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3222 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3223 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3224 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3226 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3227 return getOrCreateMethodType(Method, F);
3229 const auto *FTy = FnType->getAs<FunctionType>();
3230 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3232 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3233 // Add "self" and "_cmd"
3234 SmallVector<llvm::Metadata *, 16> Elts;
3236 // First element is always return type. For 'void' functions it is NULL.
3237 QualType ResultTy = OMethod->getReturnType();
3239 // Replace the instancetype keyword with the actual type.
3240 if (ResultTy == CGM.getContext().getObjCInstanceType())
3241 ResultTy = CGM.getContext().getPointerType(
3242 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3244 Elts.push_back(getOrCreateType(ResultTy, F));
3245 // "self" pointer is always first argument.
3246 QualType SelfDeclTy;
3247 if (auto *SelfDecl = OMethod->getSelfDecl())
3248 SelfDeclTy = SelfDecl->getType();
3249 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3250 if (FPT->getNumParams() > 1)
3251 SelfDeclTy = FPT->getParamType(0);
3252 if (!SelfDeclTy.isNull())
3254 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3255 // "_cmd" pointer is always second argument.
3256 Elts.push_back(DBuilder.createArtificialType(
3257 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3258 // Get rest of the arguments.
3259 for (const auto *PI : OMethod->parameters())
3260 Elts.push_back(getOrCreateType(PI->getType(), F));
3261 // Variadic methods need a special marker at the end of the type list.
3262 if (OMethod->isVariadic())
3263 Elts.push_back(DBuilder.createUnspecifiedParameter());
3265 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3266 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3270 // Handle variadic function types; they need an additional
3271 // unspecified parameter.
3272 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3273 if (FD->isVariadic()) {
3274 SmallVector<llvm::Metadata *, 16> EltTys;
3275 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3276 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3277 for (QualType ParamType : FPT->param_types())
3278 EltTys.push_back(getOrCreateType(ParamType, F));
3279 EltTys.push_back(DBuilder.createUnspecifiedParameter());
3280 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3281 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3285 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3288 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3289 SourceLocation ScopeLoc, QualType FnType,
3290 llvm::Function *Fn, bool CurFuncIsThunk,
3291 CGBuilderTy &Builder) {
3294 StringRef LinkageName;
3296 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3298 const Decl *D = GD.getDecl();
3299 bool HasDecl = (D != nullptr);
3301 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3302 llvm::DIFile *Unit = getOrCreateFile(Loc);
3303 llvm::DIScope *FDContext = Unit;
3304 llvm::DINodeArray TParamsArray;
3306 // Use llvm function name.
3307 LinkageName = Fn->getName();
3308 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3309 // If there is a subprogram for this function available then use it.
3310 auto FI = SPCache.find(FD->getCanonicalDecl());
3311 if (FI != SPCache.end()) {
3312 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3313 if (SP && SP->isDefinition()) {
3314 LexicalBlockStack.emplace_back(SP);
3315 RegionMap[D].reset(SP);
3319 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3320 TParamsArray, Flags);
3321 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3322 Name = getObjCMethodName(OMD);
3323 Flags |= llvm::DINode::FlagPrototyped;
3325 // Use llvm function name.
3326 Name = Fn->getName();
3327 Flags |= llvm::DINode::FlagPrototyped;
3329 if (Name.startswith("\01"))
3330 Name = Name.substr(1);
3332 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3333 Flags |= llvm::DINode::FlagArtificial;
3334 // Artificial functions should not silently reuse CurLoc.
3335 CurLoc = SourceLocation();
3339 Flags |= llvm::DINode::FlagThunk;
3341 unsigned LineNo = getLineNumber(Loc);
3342 unsigned ScopeLine = getLineNumber(ScopeLoc);
3344 // FIXME: The function declaration we're constructing here is mostly reusing
3345 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3346 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3347 // all subprograms instead of the actual context since subprogram definitions
3348 // are emitted as CU level entities by the backend.
3349 llvm::DISubprogram *SP = DBuilder.createFunction(
3350 FDContext, Name, LinkageName, Unit, LineNo,
3351 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
3352 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3353 TParamsArray.get(), getFunctionDeclaration(D));
3354 Fn->setSubprogram(SP);
3355 // We might get here with a VarDecl in the case we're generating
3356 // code for the initialization of globals. Do not record these decls
3357 // as they will overwrite the actual VarDecl Decl in the cache.
3358 if (HasDecl && isa<FunctionDecl>(D))
3359 DeclCache[D->getCanonicalDecl()].reset(SP);
3361 if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
3362 // Starting with DWARF V5 method declarations are emitted as children of
3363 // the interface type.
3364 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
3365 const ObjCInterfaceDecl *ID = OMD->getClassInterface();
3366 QualType QTy(ID->getTypeForDecl(), 0);
3367 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3368 if (It != TypeCache.end()) {
3369 llvm::DICompositeType *InterfaceDecl =
3370 cast<llvm::DICompositeType>(It->second);
3371 llvm::DISubprogram *FD = DBuilder.createFunction(
3372 InterfaceDecl, Name, LinkageName, Unit, LineNo,
3373 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
3374 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3375 TParamsArray.get());
3376 DBuilder.finalizeSubprogram(FD);
3377 ObjCMethodCache[ID].push_back(FD);
3382 // Push the function onto the lexical block stack.
3383 LexicalBlockStack.emplace_back(SP);
3386 RegionMap[D].reset(SP);
3389 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3392 StringRef LinkageName;
3394 const Decl *D = GD.getDecl();
3398 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3399 llvm::DIFile *Unit = getOrCreateFile(Loc);
3400 llvm::DIScope *FDContext = getDeclContextDescriptor(D);
3401 llvm::DINodeArray TParamsArray;
3402 if (isa<FunctionDecl>(D)) {
3403 // If there is a DISubprogram for this function available then use it.
3404 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3405 TParamsArray, Flags);
3406 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3407 Name = getObjCMethodName(OMD);
3408 Flags |= llvm::DINode::FlagPrototyped;
3410 llvm_unreachable("not a function or ObjC method");
3412 if (!Name.empty() && Name[0] == '\01')
3413 Name = Name.substr(1);
3415 if (D->isImplicit()) {
3416 Flags |= llvm::DINode::FlagArtificial;
3417 // Artificial functions without a location should not silently reuse CurLoc.
3418 if (Loc.isInvalid())
3419 CurLoc = SourceLocation();
3421 unsigned LineNo = getLineNumber(Loc);
3422 unsigned ScopeLine = 0;
3424 DBuilder.retainType(DBuilder.createFunction(
3425 FDContext, Name, LinkageName, Unit, LineNo,
3426 getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
3427 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3428 TParamsArray.get(), getFunctionDeclaration(D)));
3431 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3432 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3433 // If there is a subprogram for this function available then use it.
3434 auto FI = SPCache.find(FD->getCanonicalDecl());
3435 llvm::DISubprogram *SP = nullptr;
3436 if (FI != SPCache.end())
3437 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3438 if (!SP || !SP->isDefinition())
3439 SP = getFunctionStub(GD);
3440 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3441 LexicalBlockStack.emplace_back(SP);
3442 setInlinedAt(Builder.getCurrentDebugLocation());
3443 EmitLocation(Builder, FD->getLocation());
3446 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3447 assert(CurInlinedAt && "unbalanced inline scope stack");
3448 EmitFunctionEnd(Builder, nullptr);
3449 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3452 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3453 // Update our current location
3456 if (CurLoc.isInvalid() || CurLoc.isMacroID())
3459 llvm::MDNode *Scope = LexicalBlockStack.back();
3460 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3461 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3464 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3465 llvm::MDNode *Back = nullptr;
3466 if (!LexicalBlockStack.empty())
3467 Back = LexicalBlockStack.back().get();
3468 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3469 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3470 getColumnNumber(CurLoc)));
3473 void CGDebugInfo::AppendAddressSpaceXDeref(
3474 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
3475 Optional<unsigned> DWARFAddressSpace =
3476 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3477 if (!DWARFAddressSpace)
3480 Expr.push_back(llvm::dwarf::DW_OP_constu);
3481 Expr.push_back(DWARFAddressSpace.getValue());
3482 Expr.push_back(llvm::dwarf::DW_OP_swap);
3483 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3486 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3487 SourceLocation Loc) {
3488 // Set our current location.
3491 // Emit a line table change for the current location inside the new scope.
3492 Builder.SetCurrentDebugLocation(
3493 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3494 LexicalBlockStack.back(), CurInlinedAt));
3496 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3499 // Create a new lexical block and push it on the stack.
3500 CreateLexicalBlock(Loc);
3503 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3504 SourceLocation Loc) {
3505 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3507 // Provide an entry in the line table for the end of the block.
3508 EmitLocation(Builder, Loc);
3510 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3513 LexicalBlockStack.pop_back();
3516 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3517 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3518 unsigned RCount = FnBeginRegionCount.back();
3519 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3521 // Pop all regions for this function.
3522 while (LexicalBlockStack.size() != RCount) {
3523 // Provide an entry in the line table for the end of the block.
3524 EmitLocation(Builder, CurLoc);
3525 LexicalBlockStack.pop_back();
3527 FnBeginRegionCount.pop_back();
3529 if (Fn && Fn->getSubprogram())
3530 DBuilder.finalizeSubprogram(Fn->getSubprogram());
3533 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3534 uint64_t *XOffset) {
3536 SmallVector<llvm::Metadata *, 5> EltTys;
3538 uint64_t FieldSize, FieldOffset;
3539 uint32_t FieldAlign;
3541 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3542 QualType Type = VD->getType();
3545 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3546 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3547 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3548 FType = CGM.getContext().IntTy;
3549 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3550 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3552 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3553 if (HasCopyAndDispose) {
3554 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3556 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3558 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3560 bool HasByrefExtendedLayout;
3561 Qualifiers::ObjCLifetime Lifetime;
3562 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3563 HasByrefExtendedLayout) &&
3564 HasByrefExtendedLayout) {
3565 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3567 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3570 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3571 if (Align > CGM.getContext().toCharUnitsFromBits(
3572 CGM.getTarget().getPointerAlign(0))) {
3573 CharUnits FieldOffsetInBytes =
3574 CGM.getContext().toCharUnitsFromBits(FieldOffset);
3575 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3576 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3578 if (NumPaddingBytes.isPositive()) {
3579 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3580 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3581 pad, ArrayType::Normal, 0);
3582 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3587 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
3588 FieldSize = CGM.getContext().getTypeSize(FType);
3589 FieldAlign = CGM.getContext().toBits(Align);
3591 *XOffset = FieldOffset;
3592 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
3593 FieldAlign, FieldOffset,
3594 llvm::DINode::FlagZero, FieldTy);
3595 EltTys.push_back(FieldTy);
3596 FieldOffset += FieldSize;
3598 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3600 llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct;
3602 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
3606 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3607 llvm::Value *Storage,
3608 llvm::Optional<unsigned> ArgNo,
3609 CGBuilderTy &Builder) {
3610 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3611 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3612 if (VD->hasAttr<NoDebugAttr>())
3616 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3617 cast<Decl>(VD->getDeclContext())->isImplicit());
3618 llvm::DIFile *Unit = nullptr;
3620 Unit = getOrCreateFile(VD->getLocation());
3622 uint64_t XOffset = 0;
3623 if (VD->hasAttr<BlocksAttr>())
3624 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3626 Ty = getOrCreateType(VD->getType(), Unit);
3628 // If there is no debug info for this type then do not emit debug info
3629 // for this variable.
3633 // Get location information.
3635 unsigned Column = 0;
3637 Line = getLineNumber(VD->getLocation());
3638 Column = getColumnNumber(VD->getLocation());
3640 SmallVector<int64_t, 13> Expr;
3641 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3642 if (VD->isImplicit())
3643 Flags |= llvm::DINode::FlagArtificial;
3645 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3647 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
3648 AppendAddressSpaceXDeref(AddressSpace, Expr);
3650 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
3651 // object pointer flag.
3652 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
3653 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
3654 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3655 Flags |= llvm::DINode::FlagObjectPointer;
3658 // Note: Older versions of clang used to emit byval references with an extra
3659 // DW_OP_deref, because they referenced the IR arg directly instead of
3660 // referencing an alloca. Newer versions of LLVM don't treat allocas
3661 // differently from other function arguments when used in a dbg.declare.
3662 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3663 StringRef Name = VD->getName();
3664 if (!Name.empty()) {
3665 if (VD->hasAttr<BlocksAttr>()) {
3666 // Here, we need an offset *into* the alloca.
3667 CharUnits offset = CharUnits::fromQuantity(32);
3668 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3669 // offset of __forwarding field
3670 offset = CGM.getContext().toCharUnitsFromBits(
3671 CGM.getTarget().getPointerWidth(0));
3672 Expr.push_back(offset.getQuantity());
3673 Expr.push_back(llvm::dwarf::DW_OP_deref);
3674 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3675 // offset of x field
3676 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3677 Expr.push_back(offset.getQuantity());
3679 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
3680 // If VD is an anonymous union then Storage represents value for
3681 // all union fields.
3682 const RecordDecl *RD = RT->getDecl();
3683 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3684 // GDB has trouble finding local variables in anonymous unions, so we emit
3685 // artificial local variables for each of the members.
3687 // FIXME: Remove this code as soon as GDB supports this.
3688 // The debug info verifier in LLVM operates based on the assumption that a
3689 // variable has the same size as its storage and we had to disable the
3690 // check for artificial variables.
3691 for (const auto *Field : RD->fields()) {
3692 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3693 StringRef FieldName = Field->getName();
3695 // Ignore unnamed fields. Do not ignore unnamed records.
3696 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3699 // Use VarDecl's Tag, Scope and Line number.
3700 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
3701 auto *D = DBuilder.createAutoVariable(
3702 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3703 Flags | llvm::DINode::FlagArtificial, FieldAlign);
3705 // Insert an llvm.dbg.declare into the current block.
3706 DBuilder.insertDeclare(
3707 Storage, D, DBuilder.createExpression(Expr),
3708 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3709 Builder.GetInsertBlock());
3714 // Create the descriptor for the variable.
3715 auto *D = ArgNo ? DBuilder.createParameterVariable(
3716 Scope, Name, *ArgNo, Unit, Line, Ty,
3717 CGM.getLangOpts().Optimize, Flags)
3718 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3719 CGM.getLangOpts().Optimize,
3722 // Insert an llvm.dbg.declare into the current block.
3723 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3724 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3725 Builder.GetInsertBlock());
3730 llvm::DILocalVariable *
3731 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
3732 CGBuilderTy &Builder) {
3733 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3734 return EmitDeclare(VD, Storage, llvm::None, Builder);
3737 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3739 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3742 return DBuilder.createObjectPointerType(Ty);
3745 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3746 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3747 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3748 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3749 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3751 if (Builder.GetInsertBlock() == nullptr)
3753 if (VD->hasAttr<NoDebugAttr>())
3756 bool isByRef = VD->hasAttr<BlocksAttr>();
3758 uint64_t XOffset = 0;
3759 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3762 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3764 Ty = getOrCreateType(VD->getType(), Unit);
3766 // Self is passed along as an implicit non-arg variable in a
3767 // block. Mark it as the object pointer.
3768 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
3769 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3770 Ty = CreateSelfType(VD->getType(), Ty);
3772 // Get location information.
3773 unsigned Line = getLineNumber(VD->getLocation());
3774 unsigned Column = getColumnNumber(VD->getLocation());
3776 const llvm::DataLayout &target = CGM.getDataLayout();
3778 CharUnits offset = CharUnits::fromQuantity(
3779 target.getStructLayout(blockInfo.StructureType)
3780 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3782 SmallVector<int64_t, 9> addr;
3783 addr.push_back(llvm::dwarf::DW_OP_deref);
3784 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3785 addr.push_back(offset.getQuantity());
3787 addr.push_back(llvm::dwarf::DW_OP_deref);
3788 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3789 // offset of __forwarding field
3791 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3792 addr.push_back(offset.getQuantity());
3793 addr.push_back(llvm::dwarf::DW_OP_deref);
3794 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
3795 // offset of x field
3796 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3797 addr.push_back(offset.getQuantity());
3800 // Create the descriptor for the variable.
3801 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3802 auto *D = DBuilder.createAutoVariable(
3803 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3804 Line, Ty, false, llvm::DINode::FlagZero, Align);
3806 // Insert an llvm.dbg.declare into the current block.
3808 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
3809 auto *Expr = DBuilder.createExpression(addr);
3811 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
3813 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
3816 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3818 CGBuilderTy &Builder) {
3819 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3820 EmitDeclare(VD, AI, ArgNo, Builder);
3824 struct BlockLayoutChunk {
3825 uint64_t OffsetInBits;
3826 const BlockDecl::Capture *Capture;
3828 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3829 return l.OffsetInBits < r.OffsetInBits;
3833 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3836 llvm::AllocaInst *Alloca,
3837 CGBuilderTy &Builder) {
3838 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3839 ASTContext &C = CGM.getContext();
3840 const BlockDecl *blockDecl = block.getBlockDecl();
3842 // Collect some general information about the block's location.
3843 SourceLocation loc = blockDecl->getCaretLocation();
3844 llvm::DIFile *tunit = getOrCreateFile(loc);
3845 unsigned line = getLineNumber(loc);
3846 unsigned column = getColumnNumber(loc);
3848 // Build the debug-info type for the block literal.
3849 getDeclContextDescriptor(blockDecl);
3851 const llvm::StructLayout *blockLayout =
3852 CGM.getDataLayout().getStructLayout(block.StructureType);
3854 SmallVector<llvm::Metadata *, 16> fields;
3855 if (CGM.getLangOpts().OpenCL) {
3856 fields.push_back(createFieldType("__size", C.IntTy, loc, AS_public,
3857 blockLayout->getElementOffsetInBits(0),
3859 fields.push_back(createFieldType("__align", C.IntTy, loc, AS_public,
3860 blockLayout->getElementOffsetInBits(1),
3863 fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
3864 blockLayout->getElementOffsetInBits(0),
3866 fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
3867 blockLayout->getElementOffsetInBits(1),
3869 fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
3870 blockLayout->getElementOffsetInBits(2),
3872 auto *FnTy = block.getBlockExpr()->getFunctionType();
3873 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3874 fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
3875 blockLayout->getElementOffsetInBits(3),
3877 fields.push_back(createFieldType(
3879 C.getPointerType(block.NeedsCopyDispose
3880 ? C.getBlockDescriptorExtendedType()
3881 : C.getBlockDescriptorType()),
3882 loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3885 // We want to sort the captures by offset, not because DWARF
3886 // requires this, but because we're paranoid about debuggers.
3887 SmallVector<BlockLayoutChunk, 8> chunks;
3890 if (blockDecl->capturesCXXThis()) {
3891 BlockLayoutChunk chunk;
3892 chunk.OffsetInBits =
3893 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3894 chunk.Capture = nullptr;
3895 chunks.push_back(chunk);
3898 // Variable captures.
3899 for (const auto &capture : blockDecl->captures()) {
3900 const VarDecl *variable = capture.getVariable();
3901 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3903 // Ignore constant captures.
3904 if (captureInfo.isConstant())
3907 BlockLayoutChunk chunk;
3908 chunk.OffsetInBits =
3909 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3910 chunk.Capture = &capture;
3911 chunks.push_back(chunk);
3915 llvm::array_pod_sort(chunks.begin(), chunks.end());
3917 for (const BlockLayoutChunk &Chunk : chunks) {
3918 uint64_t offsetInBits = Chunk.OffsetInBits;
3919 const BlockDecl::Capture *capture = Chunk.Capture;
3921 // If we have a null capture, this must be the C++ 'this' capture.
3925 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
3926 type = Method->getThisType(C);
3927 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
3928 type = QualType(RDecl->getTypeForDecl(), 0);
3930 llvm_unreachable("unexpected block declcontext");
3932 fields.push_back(createFieldType("this", type, loc, AS_public,
3933 offsetInBits, tunit, tunit));
3937 const VarDecl *variable = capture->getVariable();
3938 StringRef name = variable->getName();
3940 llvm::DIType *fieldType;
3941 if (capture->isByRef()) {
3942 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3943 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
3945 // FIXME: this creates a second copy of this type!
3947 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3948 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3949 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3950 PtrInfo.Width, Align, offsetInBits,
3951 llvm::DINode::FlagZero, fieldType);
3953 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
3954 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
3955 offsetInBits, Align, tunit, tunit);
3957 fields.push_back(fieldType);
3960 SmallString<36> typeName;
3961 llvm::raw_svector_ostream(typeName)
3962 << "__block_literal_" << CGM.getUniqueBlockCount();
3964 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3966 llvm::DIType *type =
3967 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3968 CGM.getContext().toBits(block.BlockSize), 0,
3969 llvm::DINode::FlagZero, nullptr, fieldsArray);
3970 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3972 // Get overall information about the block.
3973 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
3974 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3976 // Create the descriptor for the parameter.
3977 auto *debugVar = DBuilder.createParameterVariable(
3978 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
3980 // Insert an llvm.dbg.declare into the current block.
3981 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
3982 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
3983 Builder.GetInsertBlock());
3986 llvm::DIDerivedType *
3987 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3988 if (!D->isStaticDataMember())
3991 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3992 if (MI != StaticDataMemberCache.end()) {
3993 assert(MI->second && "Static data member declaration should still exist");
3997 // If the member wasn't found in the cache, lazily construct and add it to the
3998 // type (used when a limited form of the type is emitted).
3999 auto DC = D->getDeclContext();
4000 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4001 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4004 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4005 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4006 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4007 llvm::DIGlobalVariableExpression *GVE = nullptr;
4009 for (const auto *Field : RD->fields()) {
4010 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4011 StringRef FieldName = Field->getName();
4013 // Ignore unnamed fields, but recurse into anonymous records.
4014 if (FieldName.empty()) {
4015 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4016 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4020 // Use VarDecl's Tag, Scope and Line number.
4021 GVE = DBuilder.createGlobalVariableExpression(
4022 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4023 Var->hasLocalLinkage());
4024 Var->addDebugInfo(GVE);
4029 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4031 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
4032 if (D->hasAttr<NoDebugAttr>())
4035 // If we already created a DIGlobalVariable for this declaration, just attach
4036 // it to the llvm::GlobalVariable.
4037 auto Cached = DeclCache.find(D->getCanonicalDecl());
4038 if (Cached != DeclCache.end())
4039 return Var->addDebugInfo(
4040 cast<llvm::DIGlobalVariableExpression>(Cached->second));
4042 // Create global variable debug descriptor.
4043 llvm::DIFile *Unit = nullptr;
4044 llvm::DIScope *DContext = nullptr;
4046 StringRef DeclName, LinkageName;
4048 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
4050 // Attempt to store one global variable for the declaration - even if we
4051 // emit a lot of fields.
4052 llvm::DIGlobalVariableExpression *GVE = nullptr;
4054 // If this is an anonymous union then we'll want to emit a global
4055 // variable for each member of the anonymous union so that it's possible
4056 // to find the name of any field in the union.
4057 if (T->isUnionType() && DeclName.empty()) {
4058 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4059 assert(RD->isAnonymousStructOrUnion() &&
4060 "unnamed non-anonymous struct or union?");
4061 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4063 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4065 SmallVector<int64_t, 4> Expr;
4066 unsigned AddressSpace =
4067 CGM.getContext().getTargetAddressSpace(D->getType());
4068 AppendAddressSpaceXDeref(AddressSpace, Expr);
4070 GVE = DBuilder.createGlobalVariableExpression(
4071 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4072 Var->hasLocalLinkage(),
4073 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4074 getOrCreateStaticDataMemberDeclarationOrNull(D), Align);
4075 Var->addDebugInfo(GVE);
4077 DeclCache[D->getCanonicalDecl()].reset(GVE);
4080 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4081 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
4082 if (VD->hasAttr<NoDebugAttr>())
4084 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4085 // Create the descriptor for the variable.
4086 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4087 StringRef Name = VD->getName();
4088 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4089 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4090 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4091 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4092 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4094 // Do not use global variables for enums.
4097 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
4099 // Do not emit separate definitions for function local const/statics.
4100 if (isa<FunctionDecl>(VD->getDeclContext()))
4102 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4103 auto *VarD = cast<VarDecl>(VD);
4104 if (VarD->isStaticDataMember()) {
4105 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4106 getDeclContextDescriptor(VarD);
4107 // Ensure that the type is retained even though it's otherwise unreferenced.
4109 // FIXME: This is probably unnecessary, since Ty should reference RD
4110 // through its scope.
4111 RetainedTypes.push_back(
4112 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4116 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
4118 auto &GV = DeclCache[VD];
4121 llvm::DIExpression *InitExpr = nullptr;
4122 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4123 // FIXME: Add a representation for integer constants wider than 64 bits.
4126 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4127 else if (Init.isFloat())
4128 InitExpr = DBuilder.createConstantValueExpression(
4129 Init.getFloat().bitcastToAPInt().getZExtValue());
4131 GV.reset(DBuilder.createGlobalVariableExpression(
4132 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4133 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4137 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4138 if (!LexicalBlockStack.empty())
4139 return LexicalBlockStack.back();
4140 llvm::DIScope *Mod = getParentModuleOrNull(D);
4141 return getContextDescriptor(D, Mod ? Mod : TheCU);
4144 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4145 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4147 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4148 if (!NSDecl->isAnonymousNamespace() ||
4149 CGM.getCodeGenOpts().DebugExplicitImport) {
4150 auto Loc = UD.getLocation();
4151 DBuilder.createImportedModule(
4152 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4153 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4157 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4158 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4160 assert(UD.shadow_size() &&
4161 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4162 // Emitting one decl is sufficient - debuggers can detect that this is an
4163 // overloaded name & provide lookup for all the overloads.
4164 const UsingShadowDecl &USD = **UD.shadow_begin();
4166 // FIXME: Skip functions with undeduced auto return type for now since we
4167 // don't currently have the plumbing for separate declarations & definitions
4168 // of free functions and mismatched types (auto in the declaration, concrete
4169 // return type in the definition)
4170 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4171 if (const auto *AT =
4172 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
4173 if (AT->getDeducedType().isNull())
4175 if (llvm::DINode *Target =
4176 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4177 auto Loc = USD.getLocation();
4178 DBuilder.createImportedDeclaration(
4179 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4180 getOrCreateFile(Loc), getLineNumber(Loc));
4184 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4185 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4187 if (Module *M = ID.getImportedModule()) {
4188 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
4189 auto Loc = ID.getLocation();
4190 DBuilder.createImportedDeclaration(
4191 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4192 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4193 getLineNumber(Loc));
4197 llvm::DIImportedEntity *
4198 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4199 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4201 auto &VH = NamespaceAliasCache[&NA];
4203 return cast<llvm::DIImportedEntity>(VH);
4204 llvm::DIImportedEntity *R;
4205 auto Loc = NA.getLocation();
4206 if (const auto *Underlying =
4207 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4208 // This could cache & dedup here rather than relying on metadata deduping.
4209 R = DBuilder.createImportedDeclaration(
4210 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4211 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4212 getLineNumber(Loc), NA.getName());
4214 R = DBuilder.createImportedDeclaration(
4215 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4216 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4217 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4223 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4224 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4225 // if necessary, and this way multiple declarations of the same namespace in
4226 // different parent modules stay distinct.
4227 auto I = NamespaceCache.find(NSDecl);
4228 if (I != NamespaceCache.end())
4229 return cast<llvm::DINamespace>(I->second);
4231 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4232 // Don't trust the context if it is a DIModule (see comment above).
4233 llvm::DINamespace *NS =
4234 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4235 NamespaceCache[NSDecl].reset(NS);
4239 void CGDebugInfo::setDwoId(uint64_t Signature) {
4240 assert(TheCU && "no main compile unit");
4241 TheCU->setDWOId(Signature);
4244 void CGDebugInfo::finalize() {
4245 // Creating types might create further types - invalidating the current
4246 // element and the size(), so don't cache/reference them.
4247 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4248 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4249 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4250 ? CreateTypeDefinition(E.Type, E.Unit)
4252 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4255 if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
4256 // Add methods to interface.
4257 for (const auto &P : ObjCMethodCache) {
4258 if (P.second.empty())
4261 QualType QTy(P.first->getTypeForDecl(), 0);
4262 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4263 assert(It != TypeCache.end());
4265 llvm::DICompositeType *InterfaceDecl =
4266 cast<llvm::DICompositeType>(It->second);
4268 SmallVector<llvm::Metadata *, 16> EltTys;
4269 auto CurrenetElts = InterfaceDecl->getElements();
4270 EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
4271 for (auto &MD : P.second)
4272 EltTys.push_back(MD);
4273 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4274 DBuilder.replaceArrays(InterfaceDecl, Elements);
4278 for (const auto &P : ReplaceMap) {
4280 auto *Ty = cast<llvm::DIType>(P.second);
4281 assert(Ty->isForwardDecl());
4283 auto It = TypeCache.find(P.first);
4284 assert(It != TypeCache.end());
4287 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4288 cast<llvm::DIType>(It->second));
4291 for (const auto &P : FwdDeclReplaceMap) {
4293 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4294 llvm::Metadata *Repl;
4296 auto It = DeclCache.find(P.first);
4297 // If there has been no definition for the declaration, call RAUW
4298 // with ourselves, that will destroy the temporary MDNode and
4299 // replace it with a standard one, avoiding leaking memory.
4300 if (It == DeclCache.end())
4305 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4306 Repl = GVE->getVariable();
4307 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4310 // We keep our own list of retained types, because we need to look
4311 // up the final type in the type cache.
4312 for (auto &RT : RetainedTypes)
4313 if (auto MD = TypeCache[RT])
4314 DBuilder.retainType(cast<llvm::DIType>(MD));
4316 DBuilder.finalize();
4319 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4320 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
4323 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
4324 // Don't ignore in case of explicit cast where it is referenced indirectly.
4325 DBuilder.retainType(DieTy);
4328 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4329 if (LexicalBlockStack.empty())
4330 return llvm::DebugLoc();
4332 llvm::MDNode *Scope = LexicalBlockStack.back();
4333 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);