Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp
35233 views
//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This coordinates the debug information generation while generating code.9//10//===----------------------------------------------------------------------===//1112#include "CGDebugInfo.h"13#include "CGBlocks.h"14#include "CGCXXABI.h"15#include "CGObjCRuntime.h"16#include "CGRecordLayout.h"17#include "CodeGenFunction.h"18#include "CodeGenModule.h"19#include "ConstantEmitter.h"20#include "TargetInfo.h"21#include "clang/AST/ASTContext.h"22#include "clang/AST/Attr.h"23#include "clang/AST/DeclFriend.h"24#include "clang/AST/DeclObjC.h"25#include "clang/AST/DeclTemplate.h"26#include "clang/AST/Expr.h"27#include "clang/AST/RecordLayout.h"28#include "clang/AST/RecursiveASTVisitor.h"29#include "clang/AST/VTableBuilder.h"30#include "clang/Basic/CodeGenOptions.h"31#include "clang/Basic/FileManager.h"32#include "clang/Basic/SourceManager.h"33#include "clang/Basic/Version.h"34#include "clang/CodeGen/ModuleBuilder.h"35#include "clang/Frontend/FrontendOptions.h"36#include "clang/Lex/HeaderSearchOptions.h"37#include "clang/Lex/ModuleMap.h"38#include "clang/Lex/PreprocessorOptions.h"39#include "llvm/ADT/DenseSet.h"40#include "llvm/ADT/SmallVector.h"41#include "llvm/ADT/StringExtras.h"42#include "llvm/IR/Constants.h"43#include "llvm/IR/DataLayout.h"44#include "llvm/IR/DerivedTypes.h"45#include "llvm/IR/Instructions.h"46#include "llvm/IR/Intrinsics.h"47#include "llvm/IR/Metadata.h"48#include "llvm/IR/Module.h"49#include "llvm/Support/FileSystem.h"50#include "llvm/Support/MD5.h"51#include "llvm/Support/Path.h"52#include "llvm/Support/SHA1.h"53#include "llvm/Support/SHA256.h"54#include "llvm/Support/TimeProfiler.h"55#include <optional>56using namespace clang;57using namespace clang::CodeGen;5859static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {60auto TI = Ctx.getTypeInfo(Ty);61if (TI.isAlignRequired())62return TI.Align;6364// MaxFieldAlignmentAttr is the attribute added to types65// declared after #pragma pack(n).66if (auto *Decl = Ty->getAsRecordDecl())67if (Decl->hasAttr<MaxFieldAlignmentAttr>())68return TI.Align;6970return 0;71}7273static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {74return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);75}7677static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {78return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;79}8081CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)82: CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),83DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),84DBuilder(CGM.getModule()) {85CreateCompileUnit();86}8788CGDebugInfo::~CGDebugInfo() {89assert(LexicalBlockStack.empty() &&90"Region stack mismatch, stack not empty!");91}9293ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,94SourceLocation TemporaryLocation)95: CGF(&CGF) {96init(TemporaryLocation);97}9899ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,100bool DefaultToEmpty,101SourceLocation TemporaryLocation)102: CGF(&CGF) {103init(TemporaryLocation, DefaultToEmpty);104}105106void ApplyDebugLocation::init(SourceLocation TemporaryLocation,107bool DefaultToEmpty) {108auto *DI = CGF->getDebugInfo();109if (!DI) {110CGF = nullptr;111return;112}113114OriginalLocation = CGF->Builder.getCurrentDebugLocation();115116if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())117return;118119if (TemporaryLocation.isValid()) {120DI->EmitLocation(CGF->Builder, TemporaryLocation);121return;122}123124if (DefaultToEmpty) {125CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());126return;127}128129// Construct a location that has a valid scope, but no line info.130assert(!DI->LexicalBlockStack.empty());131CGF->Builder.SetCurrentDebugLocation(132llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,133DI->LexicalBlockStack.back(), DI->getInlinedAt()));134}135136ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)137: CGF(&CGF) {138init(E->getExprLoc());139}140141ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)142: CGF(&CGF) {143if (!CGF.getDebugInfo()) {144this->CGF = nullptr;145return;146}147OriginalLocation = CGF.Builder.getCurrentDebugLocation();148if (Loc)149CGF.Builder.SetCurrentDebugLocation(std::move(Loc));150}151152ApplyDebugLocation::~ApplyDebugLocation() {153// Query CGF so the location isn't overwritten when location updates are154// temporarily disabled (for C++ default function arguments)155if (CGF)156CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));157}158159ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,160GlobalDecl InlinedFn)161: CGF(&CGF) {162if (!CGF.getDebugInfo()) {163this->CGF = nullptr;164return;165}166auto &DI = *CGF.getDebugInfo();167SavedLocation = DI.getLocation();168assert((DI.getInlinedAt() ==169CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&170"CGDebugInfo and IRBuilder are out of sync");171172DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);173}174175ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {176if (!CGF)177return;178auto &DI = *CGF->getDebugInfo();179DI.EmitInlineFunctionEnd(CGF->Builder);180DI.EmitLocation(CGF->Builder, SavedLocation);181}182183void CGDebugInfo::setLocation(SourceLocation Loc) {184// If the new location isn't valid return.185if (Loc.isInvalid())186return;187188CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);189190// If we've changed files in the middle of a lexical scope go ahead191// and create a new lexical scope with file node if it's different192// from the one in the scope.193if (LexicalBlockStack.empty())194return;195196SourceManager &SM = CGM.getContext().getSourceManager();197auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());198PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);199if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))200return;201202if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {203LexicalBlockStack.pop_back();204LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(205LBF->getScope(), getOrCreateFile(CurLoc)));206} else if (isa<llvm::DILexicalBlock>(Scope) ||207isa<llvm::DISubprogram>(Scope)) {208LexicalBlockStack.pop_back();209LexicalBlockStack.emplace_back(210DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));211}212}213214llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {215llvm::DIScope *Mod = getParentModuleOrNull(D);216return getContextDescriptor(cast<Decl>(D->getDeclContext()),217Mod ? Mod : TheCU);218}219220llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,221llvm::DIScope *Default) {222if (!Context)223return Default;224225auto I = RegionMap.find(Context);226if (I != RegionMap.end()) {227llvm::Metadata *V = I->second;228return dyn_cast_or_null<llvm::DIScope>(V);229}230231// Check namespace.232if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))233return getOrCreateNamespace(NSDecl);234235if (const auto *RDecl = dyn_cast<RecordDecl>(Context))236if (!RDecl->isDependentType())237return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),238TheCU->getFile());239return Default;240}241242PrintingPolicy CGDebugInfo::getPrintingPolicy() const {243PrintingPolicy PP = CGM.getContext().getPrintingPolicy();244245// If we're emitting codeview, it's important to try to match MSVC's naming so246// that visualizers written for MSVC will trigger for our class names. In247// particular, we can't have spaces between arguments of standard templates248// like basic_string and vector, but we must have spaces between consecutive249// angle brackets that close nested template argument lists.250if (CGM.getCodeGenOpts().EmitCodeView) {251PP.MSVCFormatting = true;252PP.SplitTemplateClosers = true;253} else {254// For DWARF, printing rules are underspecified.255// SplitTemplateClosers yields better interop with GCC and GDB (PR46052).256PP.SplitTemplateClosers = true;257}258259PP.SuppressInlineNamespace = false;260PP.PrintCanonicalTypes = true;261PP.UsePreferredNames = false;262PP.AlwaysIncludeTypeForTemplateArgument = true;263PP.UseEnumerators = false;264265// Apply -fdebug-prefix-map.266PP.Callbacks = &PrintCB;267return PP;268}269270StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {271return internString(GetName(FD));272}273274StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {275SmallString<256> MethodName;276llvm::raw_svector_ostream OS(MethodName);277OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';278const DeclContext *DC = OMD->getDeclContext();279if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {280OS << OID->getName();281} else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {282OS << OID->getName();283} else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {284if (OC->IsClassExtension()) {285OS << OC->getClassInterface()->getName();286} else {287OS << OC->getIdentifier()->getNameStart() << '('288<< OC->getIdentifier()->getNameStart() << ')';289}290} else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {291OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';292}293OS << ' ' << OMD->getSelector().getAsString() << ']';294295return internString(OS.str());296}297298StringRef CGDebugInfo::getSelectorName(Selector S) {299return internString(S.getAsString());300}301302StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {303if (isa<ClassTemplateSpecializationDecl>(RD)) {304// Copy this name on the side and use its reference.305return internString(GetName(RD));306}307308// quick optimization to avoid having to intern strings that are already309// stored reliably elsewhere310if (const IdentifierInfo *II = RD->getIdentifier())311return II->getName();312313// The CodeView printer in LLVM wants to see the names of unnamed types314// because they need to have a unique identifier.315// These names are used to reconstruct the fully qualified type names.316if (CGM.getCodeGenOpts().EmitCodeView) {317if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {318assert(RD->getDeclContext() == D->getDeclContext() &&319"Typedef should not be in another decl context!");320assert(D->getDeclName().getAsIdentifierInfo() &&321"Typedef was not named!");322return D->getDeclName().getAsIdentifierInfo()->getName();323}324325if (CGM.getLangOpts().CPlusPlus) {326StringRef Name;327328ASTContext &Context = CGM.getContext();329if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))330// Anonymous types without a name for linkage purposes have their331// declarator mangled in if they have one.332Name = DD->getName();333else if (const TypedefNameDecl *TND =334Context.getTypedefNameForUnnamedTagDecl(RD))335// Anonymous types without a name for linkage purposes have their336// associate typedef mangled in if they have one.337Name = TND->getName();338339// Give lambdas a display name based on their name mangling.340if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))341if (CXXRD->isLambda())342return internString(343CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));344345if (!Name.empty()) {346SmallString<256> UnnamedType("<unnamed-type-");347UnnamedType += Name;348UnnamedType += '>';349return internString(UnnamedType);350}351}352}353354return StringRef();355}356357std::optional<llvm::DIFile::ChecksumKind>358CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {359Checksum.clear();360361if (!CGM.getCodeGenOpts().EmitCodeView &&362CGM.getCodeGenOpts().DwarfVersion < 5)363return std::nullopt;364365SourceManager &SM = CGM.getContext().getSourceManager();366std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);367if (!MemBuffer)368return std::nullopt;369370auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());371switch (CGM.getCodeGenOpts().getDebugSrcHash()) {372case clang::CodeGenOptions::DSH_MD5:373llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);374return llvm::DIFile::CSK_MD5;375case clang::CodeGenOptions::DSH_SHA1:376llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);377return llvm::DIFile::CSK_SHA1;378case clang::CodeGenOptions::DSH_SHA256:379llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);380return llvm::DIFile::CSK_SHA256;381}382llvm_unreachable("Unhandled DebugSrcHashKind enum");383}384385std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,386FileID FID) {387if (!CGM.getCodeGenOpts().EmbedSource)388return std::nullopt;389390bool SourceInvalid = false;391StringRef Source = SM.getBufferData(FID, &SourceInvalid);392393if (SourceInvalid)394return std::nullopt;395396return Source;397}398399llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {400SourceManager &SM = CGM.getContext().getSourceManager();401StringRef FileName;402FileID FID;403std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;404405if (Loc.isInvalid()) {406// The DIFile used by the CU is distinct from the main source file. Call407// createFile() below for canonicalization if the source file was specified408// with an absolute path.409FileName = TheCU->getFile()->getFilename();410CSInfo = TheCU->getFile()->getChecksum();411} else {412PresumedLoc PLoc = SM.getPresumedLoc(Loc);413FileName = PLoc.getFilename();414415if (FileName.empty()) {416FileName = TheCU->getFile()->getFilename();417} else {418FileName = PLoc.getFilename();419}420FID = PLoc.getFileID();421}422423// Cache the results.424auto It = DIFileCache.find(FileName.data());425if (It != DIFileCache.end()) {426// Verify that the information still exists.427if (llvm::Metadata *V = It->second)428return cast<llvm::DIFile>(V);429}430431// Put Checksum at a scope where it will persist past the createFile call.432SmallString<64> Checksum;433if (!CSInfo) {434std::optional<llvm::DIFile::ChecksumKind> CSKind =435computeChecksum(FID, Checksum);436if (CSKind)437CSInfo.emplace(*CSKind, Checksum);438}439return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));440}441442llvm::DIFile *CGDebugInfo::createFile(443StringRef FileName,444std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,445std::optional<StringRef> Source) {446StringRef Dir;447StringRef File;448std::string RemappedFile = remapDIPath(FileName);449std::string CurDir = remapDIPath(getCurrentDirname());450SmallString<128> DirBuf;451SmallString<128> FileBuf;452if (llvm::sys::path::is_absolute(RemappedFile)) {453// Strip the common prefix (if it is more than just "/" or "C:\") from454// current directory and FileName for a more space-efficient encoding.455auto FileIt = llvm::sys::path::begin(RemappedFile);456auto FileE = llvm::sys::path::end(RemappedFile);457auto CurDirIt = llvm::sys::path::begin(CurDir);458auto CurDirE = llvm::sys::path::end(CurDir);459for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)460llvm::sys::path::append(DirBuf, *CurDirIt);461if (llvm::sys::path::root_path(DirBuf) == DirBuf) {462// Don't strip the common prefix if it is only the root ("/" or "C:\")463// since that would make LLVM diagnostic locations confusing.464Dir = {};465File = RemappedFile;466} else {467for (; FileIt != FileE; ++FileIt)468llvm::sys::path::append(FileBuf, *FileIt);469Dir = DirBuf;470File = FileBuf;471}472} else {473if (!llvm::sys::path::is_absolute(FileName))474Dir = CurDir;475File = RemappedFile;476}477llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);478DIFileCache[FileName.data()].reset(F);479return F;480}481482std::string CGDebugInfo::remapDIPath(StringRef Path) const {483SmallString<256> P = Path;484for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))485if (llvm::sys::path::replace_path_prefix(P, From, To))486break;487return P.str().str();488}489490unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {491if (Loc.isInvalid())492return 0;493SourceManager &SM = CGM.getContext().getSourceManager();494return SM.getPresumedLoc(Loc).getLine();495}496497unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {498// We may not want column information at all.499if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)500return 0;501502// If the location is invalid then use the current column.503if (Loc.isInvalid() && CurLoc.isInvalid())504return 0;505SourceManager &SM = CGM.getContext().getSourceManager();506PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);507return PLoc.isValid() ? PLoc.getColumn() : 0;508}509510StringRef CGDebugInfo::getCurrentDirname() {511if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())512return CGM.getCodeGenOpts().DebugCompilationDir;513514if (!CWDName.empty())515return CWDName;516llvm::ErrorOr<std::string> CWD =517CGM.getFileSystem()->getCurrentWorkingDirectory();518if (!CWD)519return StringRef();520return CWDName = internString(*CWD);521}522523void CGDebugInfo::CreateCompileUnit() {524SmallString<64> Checksum;525std::optional<llvm::DIFile::ChecksumKind> CSKind;526std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;527528// Should we be asking the SourceManager for the main file name, instead of529// accepting it as an argument? This just causes the main file name to530// mismatch with source locations and create extra lexical scopes or531// mismatched debug info (a CU with a DW_AT_file of "-", because that's what532// the driver passed, but functions/other things have DW_AT_file of "<stdin>"533// because that's what the SourceManager says)534535// Get absolute path name.536SourceManager &SM = CGM.getContext().getSourceManager();537auto &CGO = CGM.getCodeGenOpts();538const LangOptions &LO = CGM.getLangOpts();539std::string MainFileName = CGO.MainFileName;540if (MainFileName.empty())541MainFileName = "<stdin>";542543// The main file name provided via the "-main-file-name" option contains just544// the file name itself with no path information. This file name may have had545// a relative path, so we look into the actual file entry for the main546// file to determine the real absolute path for the file.547std::string MainFileDir;548if (OptionalFileEntryRef MainFile =549SM.getFileEntryRefForID(SM.getMainFileID())) {550MainFileDir = std::string(MainFile->getDir().getName());551if (!llvm::sys::path::is_absolute(MainFileName)) {552llvm::SmallString<1024> MainFileDirSS(MainFileDir);553llvm::sys::path::Style Style =554LO.UseTargetPathSeparator555? (CGM.getTarget().getTriple().isOSWindows()556? llvm::sys::path::Style::windows_backslash557: llvm::sys::path::Style::posix)558: llvm::sys::path::Style::native;559llvm::sys::path::append(MainFileDirSS, Style, MainFileName);560MainFileName = std::string(561llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));562}563// If the main file name provided is identical to the input file name, and564// if the input file is a preprocessed source, use the module name for565// debug info. The module name comes from the name specified in the first566// linemarker if the input is a preprocessed source. In this case we don't567// know the content to compute a checksum.568if (MainFile->getName() == MainFileName &&569FrontendOptions::getInputKindForExtension(570MainFile->getName().rsplit('.').second)571.isPreprocessed()) {572MainFileName = CGM.getModule().getName().str();573} else {574CSKind = computeChecksum(SM.getMainFileID(), Checksum);575}576}577578llvm::dwarf::SourceLanguage LangTag;579if (LO.CPlusPlus) {580if (LO.ObjC)581LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;582else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)583LangTag = llvm::dwarf::DW_LANG_C_plus_plus;584else if (LO.CPlusPlus14)585LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;586else if (LO.CPlusPlus11)587LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;588else589LangTag = llvm::dwarf::DW_LANG_C_plus_plus;590} else if (LO.ObjC) {591LangTag = llvm::dwarf::DW_LANG_ObjC;592} else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||593CGM.getCodeGenOpts().DwarfVersion >= 5)) {594LangTag = llvm::dwarf::DW_LANG_OpenCL;595} else if (LO.RenderScript) {596LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;597} else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {598LangTag = llvm::dwarf::DW_LANG_C11;599} else if (LO.C99) {600LangTag = llvm::dwarf::DW_LANG_C99;601} else {602LangTag = llvm::dwarf::DW_LANG_C89;603}604605std::string Producer = getClangFullVersion();606607// Figure out which version of the ObjC runtime we have.608unsigned RuntimeVers = 0;609if (LO.ObjC)610RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;611612llvm::DICompileUnit::DebugEmissionKind EmissionKind;613switch (DebugKind) {614case llvm::codegenoptions::NoDebugInfo:615case llvm::codegenoptions::LocTrackingOnly:616EmissionKind = llvm::DICompileUnit::NoDebug;617break;618case llvm::codegenoptions::DebugLineTablesOnly:619EmissionKind = llvm::DICompileUnit::LineTablesOnly;620break;621case llvm::codegenoptions::DebugDirectivesOnly:622EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;623break;624case llvm::codegenoptions::DebugInfoConstructor:625case llvm::codegenoptions::LimitedDebugInfo:626case llvm::codegenoptions::FullDebugInfo:627case llvm::codegenoptions::UnusedTypeInfo:628EmissionKind = llvm::DICompileUnit::FullDebug;629break;630}631632uint64_t DwoId = 0;633auto &CGOpts = CGM.getCodeGenOpts();634// The DIFile used by the CU is distinct from the main source635// file. Its directory part specifies what becomes the636// DW_AT_comp_dir (the compilation directory), even if the source637// file was specified with an absolute path.638if (CSKind)639CSInfo.emplace(*CSKind, Checksum);640llvm::DIFile *CUFile = DBuilder.createFile(641remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,642getSource(SM, SM.getMainFileID()));643644StringRef Sysroot, SDK;645if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {646Sysroot = CGM.getHeaderSearchOpts().Sysroot;647auto B = llvm::sys::path::rbegin(Sysroot);648auto E = llvm::sys::path::rend(Sysroot);649auto It =650std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });651if (It != E)652SDK = *It;653}654655llvm::DICompileUnit::DebugNameTableKind NameTableKind =656static_cast<llvm::DICompileUnit::DebugNameTableKind>(657CGOpts.DebugNameTable);658if (CGM.getTarget().getTriple().isNVPTX())659NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;660else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)661NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;662663// Create new compile unit.664TheCU = DBuilder.createCompileUnit(665LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",666LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,667CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,668DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,669NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);670}671672llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {673llvm::dwarf::TypeKind Encoding;674StringRef BTName;675switch (BT->getKind()) {676#define BUILTIN_TYPE(Id, SingletonId)677#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:678#include "clang/AST/BuiltinTypes.def"679case BuiltinType::Dependent:680llvm_unreachable("Unexpected builtin type");681case BuiltinType::NullPtr:682return DBuilder.createNullPtrType();683case BuiltinType::Void:684return nullptr;685case BuiltinType::ObjCClass:686if (!ClassTy)687ClassTy =688DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,689"objc_class", TheCU, TheCU->getFile(), 0);690return ClassTy;691case BuiltinType::ObjCId: {692// typedef struct objc_class *Class;693// typedef struct objc_object {694// Class isa;695// } *id;696697if (ObjTy)698return ObjTy;699700if (!ClassTy)701ClassTy =702DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,703"objc_class", TheCU, TheCU->getFile(), 0);704705unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);706707auto *ISATy = DBuilder.createPointerType(ClassTy, Size);708709ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,7100, 0, llvm::DINode::FlagZero, nullptr,711llvm::DINodeArray());712713DBuilder.replaceArrays(714ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(715ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,716llvm::DINode::FlagZero, ISATy)));717return ObjTy;718}719case BuiltinType::ObjCSel: {720if (!SelTy)721SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,722"objc_selector", TheCU,723TheCU->getFile(), 0);724return SelTy;725}726727#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \728case BuiltinType::Id: \729return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \730SingletonId);731#include "clang/Basic/OpenCLImageTypes.def"732case BuiltinType::OCLSampler:733return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);734case BuiltinType::OCLEvent:735return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);736case BuiltinType::OCLClkEvent:737return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);738case BuiltinType::OCLQueue:739return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);740case BuiltinType::OCLReserveID:741return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);742#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \743case BuiltinType::Id: \744return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);745#include "clang/Basic/OpenCLExtensionTypes.def"746747#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:748#include "clang/Basic/AArch64SVEACLETypes.def"749{750ASTContext::BuiltinVectorTypeInfo Info =751// For svcount_t, only the lower 2 bytes are relevant.752BT->getKind() == BuiltinType::SveCount753? ASTContext::BuiltinVectorTypeInfo(754CGM.getContext().BoolTy, llvm::ElementCount::getFixed(16),7551)756: CGM.getContext().getBuiltinVectorTypeInfo(BT);757758// A single vector of bytes may not suffice as the representation of759// svcount_t tuples because of the gap between the active 16bits of760// successive tuple members. Currently no such tuples are defined for761// svcount_t, so assert that NumVectors is 1.762assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) &&763"Unsupported number of vectors for svcount_t");764765// Debuggers can't extract 1bit from a vector, so will display a766// bitpattern for predicates instead.767unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors;768if (Info.ElementType == CGM.getContext().BoolTy) {769NumElems /= 8;770Info.ElementType = CGM.getContext().UnsignedCharTy;771}772773llvm::Metadata *LowerBound, *UpperBound;774LowerBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(775llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));776if (Info.EC.isScalable()) {777unsigned NumElemsPerVG = NumElems / 2;778SmallVector<uint64_t, 9> Expr(779{llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,780/* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,781llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});782UpperBound = DBuilder.createExpression(Expr);783} else784UpperBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(785llvm::Type::getInt64Ty(CGM.getLLVMContext()), NumElems - 1));786787llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(788/*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);789llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);790llvm::DIType *ElemTy =791getOrCreateType(Info.ElementType, TheCU->getFile());792auto Align = getTypeAlignIfRequired(BT, CGM.getContext());793return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,794SubscriptArray);795}796// It doesn't make sense to generate debug info for PowerPC MMA vector types.797// So we return a safe type here to avoid generating an error.798#define PPC_VECTOR_TYPE(Name, Id, size) \799case BuiltinType::Id:800#include "clang/Basic/PPCTypes.def"801return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));802803#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:804#include "clang/Basic/RISCVVTypes.def"805{806ASTContext::BuiltinVectorTypeInfo Info =807CGM.getContext().getBuiltinVectorTypeInfo(BT);808809unsigned ElementCount = Info.EC.getKnownMinValue();810unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);811812bool Fractional = false;813unsigned LMUL;814unsigned FixedSize = ElementCount * SEW;815if (Info.ElementType == CGM.getContext().BoolTy) {816// Mask type only occupies one vector register.817LMUL = 1;818} else if (FixedSize < 64) {819// In RVV scalable vector types, we encode 64 bits in the fixed part.820Fractional = true;821LMUL = 64 / FixedSize;822} else {823LMUL = FixedSize / 64;824}825826// Element count = (VLENB / SEW) x LMUL827SmallVector<uint64_t, 12> Expr(828// The DW_OP_bregx operation has two operands: a register which is829// specified by an unsigned LEB128 number, followed by a signed LEB128830// offset.831{llvm::dwarf::DW_OP_bregx, // Read the contents of a register.8324096 + 0xC22, // RISC-V VLENB CSR register.8330, // Offset for DW_OP_bregx. It is dummy here.834llvm::dwarf::DW_OP_constu,835SEW / 8, // SEW is in bits.836llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});837if (Fractional)838Expr.push_back(llvm::dwarf::DW_OP_div);839else840Expr.push_back(llvm::dwarf::DW_OP_mul);841// Element max index = count - 1842Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});843844auto *LowerBound =845llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(846llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));847auto *UpperBound = DBuilder.createExpression(Expr);848llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(849/*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);850llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);851llvm::DIType *ElemTy =852getOrCreateType(Info.ElementType, TheCU->getFile());853854auto Align = getTypeAlignIfRequired(BT, CGM.getContext());855return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,856SubscriptArray);857}858859#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \860case BuiltinType::Id: { \861if (!SingletonId) \862SingletonId = \863DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \864MangledName, TheCU, TheCU->getFile(), 0); \865return SingletonId; \866}867#include "clang/Basic/WebAssemblyReferenceTypes.def"868#define AMDGPU_OPAQUE_PTR_TYPE(Name, MangledName, AS, Width, Align, Id, \869SingletonId) \870case BuiltinType::Id: { \871if (!SingletonId) \872SingletonId = \873DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \874MangledName, TheCU, TheCU->getFile(), 0); \875return SingletonId; \876}877#include "clang/Basic/AMDGPUTypes.def"878case BuiltinType::UChar:879case BuiltinType::Char_U:880Encoding = llvm::dwarf::DW_ATE_unsigned_char;881break;882case BuiltinType::Char_S:883case BuiltinType::SChar:884Encoding = llvm::dwarf::DW_ATE_signed_char;885break;886case BuiltinType::Char8:887case BuiltinType::Char16:888case BuiltinType::Char32:889Encoding = llvm::dwarf::DW_ATE_UTF;890break;891case BuiltinType::UShort:892case BuiltinType::UInt:893case BuiltinType::UInt128:894case BuiltinType::ULong:895case BuiltinType::WChar_U:896case BuiltinType::ULongLong:897Encoding = llvm::dwarf::DW_ATE_unsigned;898break;899case BuiltinType::Short:900case BuiltinType::Int:901case BuiltinType::Int128:902case BuiltinType::Long:903case BuiltinType::WChar_S:904case BuiltinType::LongLong:905Encoding = llvm::dwarf::DW_ATE_signed;906break;907case BuiltinType::Bool:908Encoding = llvm::dwarf::DW_ATE_boolean;909break;910case BuiltinType::Half:911case BuiltinType::Float:912case BuiltinType::LongDouble:913case BuiltinType::Float16:914case BuiltinType::BFloat16:915case BuiltinType::Float128:916case BuiltinType::Double:917case BuiltinType::Ibm128:918// FIXME: For targets where long double, __ibm128 and __float128 have the919// same size, they are currently indistinguishable in the debugger without920// some special treatment. However, there is currently no consensus on921// encoding and this should be updated once a DWARF encoding exists for922// distinct floating point types of the same size.923Encoding = llvm::dwarf::DW_ATE_float;924break;925case BuiltinType::ShortAccum:926case BuiltinType::Accum:927case BuiltinType::LongAccum:928case BuiltinType::ShortFract:929case BuiltinType::Fract:930case BuiltinType::LongFract:931case BuiltinType::SatShortFract:932case BuiltinType::SatFract:933case BuiltinType::SatLongFract:934case BuiltinType::SatShortAccum:935case BuiltinType::SatAccum:936case BuiltinType::SatLongAccum:937Encoding = llvm::dwarf::DW_ATE_signed_fixed;938break;939case BuiltinType::UShortAccum:940case BuiltinType::UAccum:941case BuiltinType::ULongAccum:942case BuiltinType::UShortFract:943case BuiltinType::UFract:944case BuiltinType::ULongFract:945case BuiltinType::SatUShortAccum:946case BuiltinType::SatUAccum:947case BuiltinType::SatULongAccum:948case BuiltinType::SatUShortFract:949case BuiltinType::SatUFract:950case BuiltinType::SatULongFract:951Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;952break;953}954955BTName = BT->getName(CGM.getLangOpts());956// Bit size and offset of the type.957uint64_t Size = CGM.getContext().getTypeSize(BT);958return DBuilder.createBasicType(BTName, Size, Encoding);959}960961llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {962963StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";964llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()965? llvm::dwarf::DW_ATE_unsigned966: llvm::dwarf::DW_ATE_signed;967968return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),969Encoding);970}971972llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {973// Bit size and offset of the type.974llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;975if (Ty->isComplexIntegerType())976Encoding = llvm::dwarf::DW_ATE_lo_user;977978uint64_t Size = CGM.getContext().getTypeSize(Ty);979return DBuilder.createBasicType("complex", Size, Encoding);980}981982static void stripUnusedQualifiers(Qualifiers &Q) {983// Ignore these qualifiers for now.984Q.removeObjCGCAttr();985Q.removeAddressSpace();986Q.removeObjCLifetime();987Q.removeUnaligned();988}989990static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {991if (Q.hasConst()) {992Q.removeConst();993return llvm::dwarf::DW_TAG_const_type;994}995if (Q.hasVolatile()) {996Q.removeVolatile();997return llvm::dwarf::DW_TAG_volatile_type;998}999if (Q.hasRestrict()) {1000Q.removeRestrict();1001return llvm::dwarf::DW_TAG_restrict_type;1002}1003return (llvm::dwarf::Tag)0;1004}10051006llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,1007llvm::DIFile *Unit) {1008QualifierCollector Qc;1009const Type *T = Qc.strip(Ty);10101011stripUnusedQualifiers(Qc);10121013// We will create one Derived type for one qualifier and recurse to handle any1014// additional ones.1015llvm::dwarf::Tag Tag = getNextQualifier(Qc);1016if (!Tag) {1017assert(Qc.empty() && "Unknown type qualifier for debug info");1018return getOrCreateType(QualType(T, 0), Unit);1019}10201021auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);10221023// No need to fill in the Name, Line, Size, Alignment, Offset in case of1024// CVR derived types.1025return DBuilder.createQualifiedType(Tag, FromTy);1026}10271028llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,1029llvm::DIFile *Unit) {1030FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();1031Qualifiers &Q = EPI.TypeQuals;1032stripUnusedQualifiers(Q);10331034// We will create one Derived type for one qualifier and recurse to handle any1035// additional ones.1036llvm::dwarf::Tag Tag = getNextQualifier(Q);1037if (!Tag) {1038assert(Q.empty() && "Unknown type qualifier for debug info");1039return nullptr;1040}10411042auto *FromTy =1043getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),1044F->getParamTypes(), EPI),1045Unit);10461047// No need to fill in the Name, Line, Size, Alignment, Offset in case of1048// CVR derived types.1049return DBuilder.createQualifiedType(Tag, FromTy);1050}10511052llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,1053llvm::DIFile *Unit) {10541055// The frontend treats 'id' as a typedef to an ObjCObjectType,1056// whereas 'id<protocol>' is treated as an ObjCPointerType. For the1057// debug info, we want to emit 'id' in both cases.1058if (Ty->isObjCQualifiedIdType())1059return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);10601061return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,1062Ty->getPointeeType(), Unit);1063}10641065llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,1066llvm::DIFile *Unit) {1067return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,1068Ty->getPointeeType(), Unit);1069}10701071/// \return whether a C++ mangling exists for the type defined by TD.1072static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {1073switch (TheCU->getSourceLanguage()) {1074case llvm::dwarf::DW_LANG_C_plus_plus:1075case llvm::dwarf::DW_LANG_C_plus_plus_11:1076case llvm::dwarf::DW_LANG_C_plus_plus_14:1077return true;1078case llvm::dwarf::DW_LANG_ObjC_plus_plus:1079return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);1080default:1081return false;1082}1083}10841085// Determines if the debug info for this tag declaration needs a type1086// identifier. The purpose of the unique identifier is to deduplicate type1087// information for identical types across TUs. Because of the C++ one definition1088// rule (ODR), it is valid to assume that the type is defined the same way in1089// every TU and its debug info is equivalent.1090//1091// C does not have the ODR, and it is common for codebases to contain multiple1092// different definitions of a struct with the same name in different TUs.1093// Therefore, if the type doesn't have a C++ mangling, don't give it an1094// identifer. Type information in C is smaller and simpler than C++ type1095// information, so the increase in debug info size is negligible.1096//1097// If the type is not externally visible, it should be unique to the current TU,1098// and should not need an identifier to participate in type deduplication.1099// However, when emitting CodeView, the format internally uses these1100// unique type name identifers for references between debug info. For example,1101// the method of a class in an anonymous namespace uses the identifer to refer1102// to its parent class. The Microsoft C++ ABI attempts to provide unique names1103// for such types, so when emitting CodeView, always use identifiers for C++1104// types. This may create problems when attempting to emit CodeView when the MS1105// C++ ABI is not in use.1106static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,1107llvm::DICompileUnit *TheCU) {1108// We only add a type identifier for types with C++ name mangling.1109if (!hasCXXMangling(TD, TheCU))1110return false;11111112// Externally visible types with C++ mangling need a type identifier.1113if (TD->isExternallyVisible())1114return true;11151116// CodeView types with C++ mangling need a type identifier.1117if (CGM.getCodeGenOpts().EmitCodeView)1118return true;11191120return false;1121}11221123// Returns a unique type identifier string if one exists, or an empty string.1124static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,1125llvm::DICompileUnit *TheCU) {1126SmallString<256> Identifier;1127const TagDecl *TD = Ty->getDecl();11281129if (!needsTypeIdentifier(TD, CGM, TheCU))1130return Identifier;1131if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))1132if (RD->getDefinition())1133if (RD->isDynamicClass() &&1134CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)1135return Identifier;11361137// TODO: This is using the RTTI name. Is there a better way to get1138// a unique string for a type?1139llvm::raw_svector_ostream Out(Identifier);1140CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);1141return Identifier;1142}11431144/// \return the appropriate DWARF tag for a composite type.1145static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {1146llvm::dwarf::Tag Tag;1147if (RD->isStruct() || RD->isInterface())1148Tag = llvm::dwarf::DW_TAG_structure_type;1149else if (RD->isUnion())1150Tag = llvm::dwarf::DW_TAG_union_type;1151else {1152// FIXME: This could be a struct type giving a default visibility different1153// than C++ class type, but needs llvm metadata changes first.1154assert(RD->isClass());1155Tag = llvm::dwarf::DW_TAG_class_type;1156}1157return Tag;1158}11591160llvm::DICompositeType *1161CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,1162llvm::DIScope *Ctx) {1163const RecordDecl *RD = Ty->getDecl();1164if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))1165return cast<llvm::DICompositeType>(T);1166llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());1167const unsigned Line =1168getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);1169StringRef RDName = getClassName(RD);11701171uint64_t Size = 0;1172uint32_t Align = 0;11731174const RecordDecl *D = RD->getDefinition();1175if (D && D->isCompleteDefinition())1176Size = CGM.getContext().getTypeSize(Ty);11771178llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;11791180// Add flag to nontrivial forward declarations. To be consistent with MSVC,1181// add the flag if a record has no definition because we don't know whether1182// it will be trivial or not.1183if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))1184if (!CXXRD->hasDefinition() ||1185(CXXRD->hasDefinition() && !CXXRD->isTrivial()))1186Flags |= llvm::DINode::FlagNonTrivial;11871188// Create the type.1189SmallString<256> Identifier;1190// Don't include a linkage name in line tables only.1191if (CGM.getCodeGenOpts().hasReducedDebugInfo())1192Identifier = getTypeIdentifier(Ty, CGM, TheCU);1193llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(1194getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,1195Identifier);1196if (CGM.getCodeGenOpts().DebugFwdTemplateParams)1197if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))1198DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),1199CollectCXXTemplateParams(TSpecial, DefUnit));1200ReplaceMap.emplace_back(1201std::piecewise_construct, std::make_tuple(Ty),1202std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));1203return RetTy;1204}12051206llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,1207const Type *Ty,1208QualType PointeeTy,1209llvm::DIFile *Unit) {1210// Bit size, align and offset of the type.1211// Size is always the size of a pointer.1212uint64_t Size = CGM.getContext().getTypeSize(Ty);1213auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());1214std::optional<unsigned> DWARFAddressSpace =1215CGM.getTarget().getDWARFAddressSpace(1216CGM.getTypes().getTargetAddressSpace(PointeeTy));12171218SmallVector<llvm::Metadata *, 4> Annots;1219auto *BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);1220while (BTFAttrTy) {1221StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();1222if (!Tag.empty()) {1223llvm::Metadata *Ops[2] = {1224llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),1225llvm::MDString::get(CGM.getLLVMContext(), Tag)};1226Annots.insert(Annots.begin(),1227llvm::MDNode::get(CGM.getLLVMContext(), Ops));1228}1229BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());1230}12311232llvm::DINodeArray Annotations = nullptr;1233if (Annots.size() > 0)1234Annotations = DBuilder.getOrCreateArray(Annots);12351236if (Tag == llvm::dwarf::DW_TAG_reference_type ||1237Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)1238return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),1239Size, Align, DWARFAddressSpace);1240else1241return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,1242Align, DWARFAddressSpace, StringRef(),1243Annotations);1244}12451246llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,1247llvm::DIType *&Cache) {1248if (Cache)1249return Cache;1250Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,1251TheCU, TheCU->getFile(), 0);1252unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);1253Cache = DBuilder.createPointerType(Cache, Size);1254return Cache;1255}12561257uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(1258const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,1259unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {1260QualType FType;12611262// Advanced by calls to CreateMemberType in increments of FType, then1263// returned as the overall size of the default elements.1264uint64_t FieldOffset = 0;12651266// Blocks in OpenCL have unique constraints which make the standard fields1267// redundant while requiring size and align fields for enqueue_kernel. See1268// initializeForBlockHeader in CGBlocks.cpp1269if (CGM.getLangOpts().OpenCL) {1270FType = CGM.getContext().IntTy;1271EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));1272EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));1273} else {1274FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);1275EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));1276FType = CGM.getContext().IntTy;1277EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));1278EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));1279FType = CGM.getContext().getPointerType(Ty->getPointeeType());1280EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));1281FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);1282uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);1283uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);1284EltTys.push_back(DBuilder.createMemberType(1285Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,1286FieldOffset, llvm::DINode::FlagZero, DescTy));1287FieldOffset += FieldSize;1288}12891290return FieldOffset;1291}12921293llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,1294llvm::DIFile *Unit) {1295SmallVector<llvm::Metadata *, 8> EltTys;1296QualType FType;1297uint64_t FieldOffset;1298llvm::DINodeArray Elements;12991300FieldOffset = 0;1301FType = CGM.getContext().UnsignedLongTy;1302EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));1303EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));13041305Elements = DBuilder.getOrCreateArray(EltTys);1306EltTys.clear();13071308llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;13091310auto *EltTy =1311DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,1312FieldOffset, 0, Flags, nullptr, Elements);13131314// Bit size, align and offset of the type.1315uint64_t Size = CGM.getContext().getTypeSize(Ty);13161317auto *DescTy = DBuilder.createPointerType(EltTy, Size);13181319FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,13200, EltTys);13211322Elements = DBuilder.getOrCreateArray(EltTys);13231324// The __block_literal_generic structs are marked with a special1325// DW_AT_APPLE_BLOCK attribute and are an implementation detail only1326// the debugger needs to know about. To allow type uniquing, emit1327// them without a name or a location.1328EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,1329Flags, nullptr, Elements);13301331return DBuilder.createPointerType(EltTy, Size);1332}13331334static llvm::SmallVector<TemplateArgument>1335GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) {1336assert(Ty->isTypeAlias());1337// TemplateSpecializationType doesn't know if its template args are1338// being substituted into a parameter pack. We can find out if that's1339// the case now by inspecting the TypeAliasTemplateDecl template1340// parameters. Insert Ty's template args into SpecArgs, bundling args1341// passed to a parameter pack into a TemplateArgument::Pack. It also1342// doesn't know the value of any defaulted args, so collect those now1343// too.1344SmallVector<TemplateArgument> SpecArgs;1345ArrayRef SubstArgs = Ty->template_arguments();1346for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {1347// If Param is a parameter pack, pack the remaining arguments.1348if (Param->isParameterPack()) {1349SpecArgs.push_back(TemplateArgument(SubstArgs));1350break;1351}13521353// Skip defaulted args.1354// FIXME: Ideally, we wouldn't do this. We can read the default values1355// for each parameter. However, defaulted arguments which are dependent1356// values or dependent types can't (easily?) be resolved here.1357if (SubstArgs.empty()) {1358// If SubstArgs is now empty (we're taking from it each iteration) and1359// this template parameter isn't a pack, then that should mean we're1360// using default values for the remaining template parameters (after1361// which there may be an empty pack too which we will ignore).1362break;1363}13641365// Take the next argument.1366SpecArgs.push_back(SubstArgs.front());1367SubstArgs = SubstArgs.drop_front();1368}1369return SpecArgs;1370}13711372llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,1373llvm::DIFile *Unit) {1374assert(Ty->isTypeAlias());1375llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);13761377const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl();1378if (isa<BuiltinTemplateDecl>(TD))1379return Src;13801381const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();1382if (AliasDecl->hasAttr<NoDebugAttr>())1383return Src;13841385SmallString<128> NS;1386llvm::raw_svector_ostream OS(NS);13871388auto PP = getPrintingPolicy();1389Ty->getTemplateName().print(OS, PP, TemplateName::Qualified::None);13901391SourceLocation Loc = AliasDecl->getLocation();13921393if (CGM.getCodeGenOpts().DebugTemplateAlias &&1394// FIXME: This is a workaround for the issue1395// https://github.com/llvm/llvm-project/issues/897741396// The TemplateSpecializationType doesn't contain any instantiation1397// information; dependent template arguments can't be resolved. For now,1398// fall back to DW_TAG_typedefs for template aliases that are1399// instantiation dependent, e.g.:1400// ```1401// template <int>1402// using A = int;1403//1404// template<int I>1405// struct S {1406// using AA = A<I>; // Instantiation dependent.1407// AA aa;1408// };1409//1410// S<0> s;1411// ```1412// S::AA's underlying type A<I> is dependent on I so will be emitted as a1413// DW_TAG_typedef.1414!Ty->isInstantiationDependentType()) {1415auto ArgVector = ::GetTemplateArgs(TD, Ty);1416TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};14171418// FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.1419// Note we can't use GetName without additional work: TypeAliasTemplateDecl1420// doesn't have instantiation information, so1421// TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the1422// template args.1423std::string Name;1424llvm::raw_string_ostream OS(Name);1425TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);1426if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=1427llvm::codegenoptions::DebugTemplateNamesKind::Simple ||1428!HasReconstitutableArgs(Args.Args))1429printTemplateArgumentList(OS, Args.Args, PP);14301431llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(1432Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),1433getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));1434return AliasTy;1435}14361437// Disable PrintCanonicalTypes here because we want1438// the DW_AT_name to benefit from the TypePrinter's ability1439// to skip defaulted template arguments.1440//1441// FIXME: Once -gsimple-template-names is enabled by default1442// and we attach template parameters to alias template DIEs1443// we don't need to worry about customizing the PrintingPolicy1444// here anymore.1445PP.PrintCanonicalTypes = false;1446printTemplateArgumentList(OS, Ty->template_arguments(), PP,1447TD->getTemplateParameters());1448return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),1449getLineNumber(Loc),1450getDeclContextDescriptor(AliasDecl));1451}14521453/// Convert an AccessSpecifier into the corresponding DINode flag.1454/// As an optimization, return 0 if the access specifier equals the1455/// default for the containing type.1456static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,1457const RecordDecl *RD) {1458AccessSpecifier Default = clang::AS_none;1459if (RD && RD->isClass())1460Default = clang::AS_private;1461else if (RD && (RD->isStruct() || RD->isUnion()))1462Default = clang::AS_public;14631464if (Access == Default)1465return llvm::DINode::FlagZero;14661467switch (Access) {1468case clang::AS_private:1469return llvm::DINode::FlagPrivate;1470case clang::AS_protected:1471return llvm::DINode::FlagProtected;1472case clang::AS_public:1473return llvm::DINode::FlagPublic;1474case clang::AS_none:1475return llvm::DINode::FlagZero;1476}1477llvm_unreachable("unexpected access enumerator");1478}14791480llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,1481llvm::DIFile *Unit) {1482llvm::DIType *Underlying =1483getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);14841485if (Ty->getDecl()->hasAttr<NoDebugAttr>())1486return Underlying;14871488// We don't set size information, but do specify where the typedef was1489// declared.1490SourceLocation Loc = Ty->getDecl()->getLocation();14911492uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());1493// Typedefs are derived from some other type.1494llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());14951496llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;1497const DeclContext *DC = Ty->getDecl()->getDeclContext();1498if (isa<RecordDecl>(DC))1499Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));15001501return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),1502getOrCreateFile(Loc), getLineNumber(Loc),1503getDeclContextDescriptor(Ty->getDecl()), Align,1504Flags, Annotations);1505}15061507static unsigned getDwarfCC(CallingConv CC) {1508switch (CC) {1509case CC_C:1510// Avoid emitting DW_AT_calling_convention if the C convention was used.1511return 0;15121513case CC_X86StdCall:1514return llvm::dwarf::DW_CC_BORLAND_stdcall;1515case CC_X86FastCall:1516return llvm::dwarf::DW_CC_BORLAND_msfastcall;1517case CC_X86ThisCall:1518return llvm::dwarf::DW_CC_BORLAND_thiscall;1519case CC_X86VectorCall:1520return llvm::dwarf::DW_CC_LLVM_vectorcall;1521case CC_X86Pascal:1522return llvm::dwarf::DW_CC_BORLAND_pascal;1523case CC_Win64:1524return llvm::dwarf::DW_CC_LLVM_Win64;1525case CC_X86_64SysV:1526return llvm::dwarf::DW_CC_LLVM_X86_64SysV;1527case CC_AAPCS:1528case CC_AArch64VectorCall:1529case CC_AArch64SVEPCS:1530return llvm::dwarf::DW_CC_LLVM_AAPCS;1531case CC_AAPCS_VFP:1532return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;1533case CC_IntelOclBicc:1534return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;1535case CC_SpirFunction:1536return llvm::dwarf::DW_CC_LLVM_SpirFunction;1537case CC_OpenCLKernel:1538case CC_AMDGPUKernelCall:1539return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;1540case CC_Swift:1541return llvm::dwarf::DW_CC_LLVM_Swift;1542case CC_SwiftAsync:1543return llvm::dwarf::DW_CC_LLVM_SwiftTail;1544case CC_PreserveMost:1545return llvm::dwarf::DW_CC_LLVM_PreserveMost;1546case CC_PreserveAll:1547return llvm::dwarf::DW_CC_LLVM_PreserveAll;1548case CC_X86RegCall:1549return llvm::dwarf::DW_CC_LLVM_X86RegCall;1550case CC_M68kRTD:1551return llvm::dwarf::DW_CC_LLVM_M68kRTD;1552case CC_PreserveNone:1553return llvm::dwarf::DW_CC_LLVM_PreserveNone;1554case CC_RISCVVectorCall:1555return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;1556}1557return 0;1558}15591560static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {1561llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;1562if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)1563Flags |= llvm::DINode::FlagLValueReference;1564if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)1565Flags |= llvm::DINode::FlagRValueReference;1566return Flags;1567}15681569llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,1570llvm::DIFile *Unit) {1571const auto *FPT = dyn_cast<FunctionProtoType>(Ty);1572if (FPT) {1573if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))1574return QTy;1575}15761577// Create the type without any qualifiers15781579SmallVector<llvm::Metadata *, 16> EltTys;15801581// Add the result type at least.1582EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));15831584llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;1585// Set up remainder of arguments if there is a prototype.1586// otherwise emit it as a variadic function.1587if (!FPT) {1588EltTys.push_back(DBuilder.createUnspecifiedParameter());1589} else {1590Flags = getRefFlags(FPT);1591for (const QualType &ParamType : FPT->param_types())1592EltTys.push_back(getOrCreateType(ParamType, Unit));1593if (FPT->isVariadic())1594EltTys.push_back(DBuilder.createUnspecifiedParameter());1595}15961597llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);1598llvm::DIType *F = DBuilder.createSubroutineType(1599EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));1600return F;1601}16021603llvm::DIDerivedType *1604CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,1605llvm::DIScope *RecordTy, const RecordDecl *RD) {1606StringRef Name = BitFieldDecl->getName();1607QualType Ty = BitFieldDecl->getType();1608if (BitFieldDecl->hasAttr<PreferredTypeAttr>())1609Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();1610SourceLocation Loc = BitFieldDecl->getLocation();1611llvm::DIFile *VUnit = getOrCreateFile(Loc);1612llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);16131614// Get the location for the field.1615llvm::DIFile *File = getOrCreateFile(Loc);1616unsigned Line = getLineNumber(Loc);16171618const CGBitFieldInfo &BitFieldInfo =1619CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);1620uint64_t SizeInBits = BitFieldInfo.Size;1621assert(SizeInBits > 0 && "found named 0-width bitfield");1622uint64_t StorageOffsetInBits =1623CGM.getContext().toBits(BitFieldInfo.StorageOffset);1624uint64_t Offset = BitFieldInfo.Offset;1625// The bit offsets for big endian machines are reversed for big1626// endian target, compensate for that as the DIDerivedType requires1627// un-reversed offsets.1628if (CGM.getDataLayout().isBigEndian())1629Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;1630uint64_t OffsetInBits = StorageOffsetInBits + Offset;1631llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);1632llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);1633return DBuilder.createBitFieldMemberType(1634RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,1635Flags, DebugType, Annotations);1636}16371638llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(1639const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,1640llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {16411642if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())1643return nullptr;16441645/*1646Add a *single* zero-bitfield separator between two non-zero bitfields1647separated by one or more zero-bitfields. This is used to distinguish between1648structures such the ones below, where the memory layout is the same, but how1649the ABI assigns fields to registers differs.16501651struct foo {1652int space[4];1653char a : 8; // on amdgpu, passed on v41654char b : 8;1655char x : 8;1656char y : 8;1657};1658struct bar {1659int space[4];1660char a : 8; // on amdgpu, passed on v41661char b : 8;1662char : 0;1663char x : 8; // passed on v51664char y : 8;1665};1666*/1667if (PreviousFieldsDI.empty())1668return nullptr;16691670// If we already emitted metadata for a 0-length bitfield, nothing to do here.1671auto *PreviousMDEntry =1672PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();1673auto *PreviousMDField =1674dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);1675if (!PreviousMDField || !PreviousMDField->isBitField() ||1676PreviousMDField->getSizeInBits() == 0)1677return nullptr;16781679auto PreviousBitfield = RD->field_begin();1680std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);16811682assert(PreviousBitfield->isBitField());16831684ASTContext &Context = CGM.getContext();1685if (!PreviousBitfield->isZeroLengthBitField(Context))1686return nullptr;16871688QualType Ty = PreviousBitfield->getType();1689SourceLocation Loc = PreviousBitfield->getLocation();1690llvm::DIFile *VUnit = getOrCreateFile(Loc);1691llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);1692llvm::DIScope *RecordTy = BitFieldDI->getScope();16931694llvm::DIFile *File = getOrCreateFile(Loc);1695unsigned Line = getLineNumber(Loc);16961697uint64_t StorageOffsetInBits =1698cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())1699->getZExtValue();17001701llvm::DINode::DIFlags Flags =1702getAccessFlag(PreviousBitfield->getAccess(), RD);1703llvm::DINodeArray Annotations =1704CollectBTFDeclTagAnnotations(*PreviousBitfield);1705return DBuilder.createBitFieldMemberType(1706RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,1707Flags, DebugType, Annotations);1708}17091710llvm::DIType *CGDebugInfo::createFieldType(1711StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,1712uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,1713llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {1714llvm::DIType *debugType = getOrCreateType(type, tunit);17151716// Get the location for the field.1717llvm::DIFile *file = getOrCreateFile(loc);1718const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);17191720uint64_t SizeInBits = 0;1721auto Align = AlignInBits;1722if (!type->isIncompleteArrayType()) {1723TypeInfo TI = CGM.getContext().getTypeInfo(type);1724SizeInBits = TI.Width;1725if (!Align)1726Align = getTypeAlignIfRequired(type, CGM.getContext());1727}17281729llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);1730return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,1731offsetInBits, flags, debugType, Annotations);1732}17331734llvm::DISubprogram *1735CGDebugInfo::createInlinedTrapSubprogram(StringRef FuncName,1736llvm::DIFile *FileScope) {1737// We are caching the subprogram because we don't want to duplicate1738// subprograms with the same message. Note that `SPFlagDefinition` prevents1739// subprograms from being uniqued.1740llvm::DISubprogram *&SP = InlinedTrapFuncMap[FuncName];17411742if (!SP) {1743llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(nullptr);1744SP = DBuilder.createFunction(1745/*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(),1746/*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy,1747/*ScopeLine=*/0,1748/*Flags=*/llvm::DINode::FlagArtificial,1749/*SPFlags=*/llvm::DISubprogram::SPFlagDefinition,1750/*TParams=*/nullptr, /*ThrownTypes=*/nullptr, /*Annotations=*/nullptr);1751}17521753return SP;1754}17551756void CGDebugInfo::CollectRecordLambdaFields(1757const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,1758llvm::DIType *RecordTy) {1759// For C++11 Lambdas a Field will be the same as a Capture, but the Capture1760// has the name and the location of the variable so we should iterate over1761// both concurrently.1762const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);1763RecordDecl::field_iterator Field = CXXDecl->field_begin();1764unsigned fieldno = 0;1765for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),1766E = CXXDecl->captures_end();1767I != E; ++I, ++Field, ++fieldno) {1768const LambdaCapture &C = *I;1769if (C.capturesVariable()) {1770SourceLocation Loc = C.getLocation();1771assert(!Field->isBitField() && "lambdas don't have bitfield members!");1772ValueDecl *V = C.getCapturedVar();1773StringRef VName = V->getName();1774llvm::DIFile *VUnit = getOrCreateFile(Loc);1775auto Align = getDeclAlignIfRequired(V, CGM.getContext());1776llvm::DIType *FieldType = createFieldType(1777VName, Field->getType(), Loc, Field->getAccess(),1778layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);1779elements.push_back(FieldType);1780} else if (C.capturesThis()) {1781// TODO: Need to handle 'this' in some way by probably renaming the1782// this of the lambda class and having a field member of 'this' or1783// by using AT_object_pointer for the function and having that be1784// used as 'this' for semantic references.1785FieldDecl *f = *Field;1786llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());1787QualType type = f->getType();1788StringRef ThisName =1789CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";1790llvm::DIType *fieldType = createFieldType(1791ThisName, type, f->getLocation(), f->getAccess(),1792layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);17931794elements.push_back(fieldType);1795}1796}1797}17981799llvm::DIDerivedType *1800CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,1801const RecordDecl *RD) {1802// Create the descriptor for the static variable, with or without1803// constant initializers.1804Var = Var->getCanonicalDecl();1805llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());1806llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);18071808unsigned LineNumber = getLineNumber(Var->getLocation());1809StringRef VName = Var->getName();18101811// FIXME: to avoid complications with type merging we should1812// emit the constant on the definition instead of the declaration.1813llvm::Constant *C = nullptr;1814if (Var->getInit()) {1815const APValue *Value = Var->evaluateValue();1816if (Value) {1817if (Value->isInt())1818C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());1819if (Value->isFloat())1820C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());1821}1822}18231824llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);1825auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 51826? llvm::dwarf::DW_TAG_variable1827: llvm::dwarf::DW_TAG_member;1828auto Align = getDeclAlignIfRequired(Var, CGM.getContext());1829llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(1830RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);1831StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);1832return GV;1833}18341835void CGDebugInfo::CollectRecordNormalField(1836const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,1837SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,1838const RecordDecl *RD) {1839StringRef name = field->getName();1840QualType type = field->getType();18411842// Ignore unnamed fields unless they're anonymous structs/unions.1843if (name.empty() && !type->isRecordType())1844return;18451846llvm::DIType *FieldType;1847if (field->isBitField()) {1848llvm::DIDerivedType *BitFieldType;1849FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);1850if (llvm::DIType *Separator =1851createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))1852elements.push_back(Separator);1853} else {1854auto Align = getDeclAlignIfRequired(field, CGM.getContext());1855llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);1856FieldType =1857createFieldType(name, type, field->getLocation(), field->getAccess(),1858OffsetInBits, Align, tunit, RecordTy, RD, Annotations);1859}18601861elements.push_back(FieldType);1862}18631864void CGDebugInfo::CollectRecordNestedType(1865const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {1866QualType Ty = CGM.getContext().getTypeDeclType(TD);1867// Injected class names are not considered nested records.1868if (isa<InjectedClassNameType>(Ty))1869return;1870SourceLocation Loc = TD->getLocation();1871llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));1872elements.push_back(nestedType);1873}18741875void CGDebugInfo::CollectRecordFields(1876const RecordDecl *record, llvm::DIFile *tunit,1877SmallVectorImpl<llvm::Metadata *> &elements,1878llvm::DICompositeType *RecordTy) {1879const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);18801881if (CXXDecl && CXXDecl->isLambda())1882CollectRecordLambdaFields(CXXDecl, elements, RecordTy);1883else {1884const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);18851886// Field number for non-static fields.1887unsigned fieldNo = 0;18881889// Static and non-static members should appear in the same order as1890// the corresponding declarations in the source program.1891for (const auto *I : record->decls())1892if (const auto *V = dyn_cast<VarDecl>(I)) {1893if (V->hasAttr<NoDebugAttr>())1894continue;18951896// Skip variable template specializations when emitting CodeView. MSVC1897// doesn't emit them.1898if (CGM.getCodeGenOpts().EmitCodeView &&1899isa<VarTemplateSpecializationDecl>(V))1900continue;19011902if (isa<VarTemplatePartialSpecializationDecl>(V))1903continue;19041905// Reuse the existing static member declaration if one exists1906auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());1907if (MI != StaticDataMemberCache.end()) {1908assert(MI->second &&1909"Static data member declaration should still exist");1910elements.push_back(MI->second);1911} else {1912auto Field = CreateRecordStaticField(V, RecordTy, record);1913elements.push_back(Field);1914}1915} else if (const auto *field = dyn_cast<FieldDecl>(I)) {1916CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,1917elements, RecordTy, record);19181919// Bump field number for next field.1920++fieldNo;1921} else if (CGM.getCodeGenOpts().EmitCodeView) {1922// Debug info for nested types is included in the member list only for1923// CodeView.1924if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {1925// MSVC doesn't generate nested type for anonymous struct/union.1926if (isa<RecordDecl>(I) &&1927cast<RecordDecl>(I)->isAnonymousStructOrUnion())1928continue;1929if (!nestedType->isImplicit() &&1930nestedType->getDeclContext() == record)1931CollectRecordNestedType(nestedType, elements);1932}1933}1934}1935}19361937llvm::DISubroutineType *1938CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,1939llvm::DIFile *Unit) {1940const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();1941if (Method->isStatic())1942return cast_or_null<llvm::DISubroutineType>(1943getOrCreateType(QualType(Func, 0), Unit));1944return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);1945}19461947llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(1948QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {1949FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();1950Qualifiers &Qc = EPI.TypeQuals;1951Qc.removeConst();1952Qc.removeVolatile();1953Qc.removeRestrict();1954Qc.removeUnaligned();1955// Keep the removed qualifiers in sync with1956// CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)1957// On a 'real' member function type, these qualifiers are carried on the type1958// of the first parameter, not as separate DW_TAG_const_type (etc) decorator1959// tags around them. (But, in the raw function types with qualifiers, they have1960// to use wrapper types.)19611962// Add "this" pointer.1963const auto *OriginalFunc = cast<llvm::DISubroutineType>(1964getOrCreateType(CGM.getContext().getFunctionType(1965Func->getReturnType(), Func->getParamTypes(), EPI),1966Unit));1967llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();1968assert(Args.size() && "Invalid number of arguments!");19691970SmallVector<llvm::Metadata *, 16> Elts;19711972// First element is always return type. For 'void' functions it is NULL.1973Elts.push_back(Args[0]);19741975// "this" pointer is always first argument.1976const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();1977if (isa<ClassTemplateSpecializationDecl>(RD)) {1978// Create pointer type directly in this case.1979const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);1980uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy);1981auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());1982llvm::DIType *PointeeType =1983getOrCreateType(ThisPtrTy->getPointeeType(), Unit);1984llvm::DIType *ThisPtrType =1985DBuilder.createPointerType(PointeeType, Size, Align);1986TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);1987// TODO: This and the artificial type below are misleading, the1988// types aren't artificial the argument is, but the current1989// metadata doesn't represent that.1990ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);1991Elts.push_back(ThisPtrType);1992} else {1993llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);1994TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);1995ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);1996Elts.push_back(ThisPtrType);1997}19981999// Copy rest of the arguments.2000for (unsigned i = 1, e = Args.size(); i != e; ++i)2001Elts.push_back(Args[i]);20022003llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);20042005return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),2006getDwarfCC(Func->getCallConv()));2007}20082009/// isFunctionLocalClass - Return true if CXXRecordDecl is defined2010/// inside a function.2011static bool isFunctionLocalClass(const CXXRecordDecl *RD) {2012if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))2013return isFunctionLocalClass(NRD);2014if (isa<FunctionDecl>(RD->getDeclContext()))2015return true;2016return false;2017}20182019llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(2020const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {2021bool IsCtorOrDtor =2022isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);20232024StringRef MethodName = getFunctionName(Method);2025llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);20262027// Since a single ctor/dtor corresponds to multiple functions, it doesn't2028// make sense to give a single ctor/dtor a linkage name.2029StringRef MethodLinkageName;2030// FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional2031// property to use here. It may've been intended to model "is non-external2032// type" but misses cases of non-function-local but non-external classes such2033// as those in anonymous namespaces as well as the reverse - external types2034// that are function local, such as those in (non-local) inline functions.2035if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))2036MethodLinkageName = CGM.getMangledName(Method);20372038// Get the location for the method.2039llvm::DIFile *MethodDefUnit = nullptr;2040unsigned MethodLine = 0;2041if (!Method->isImplicit()) {2042MethodDefUnit = getOrCreateFile(Method->getLocation());2043MethodLine = getLineNumber(Method->getLocation());2044}20452046// Collect virtual method info.2047llvm::DIType *ContainingType = nullptr;2048unsigned VIndex = 0;2049llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;2050llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;2051int ThisAdjustment = 0;20522053if (VTableContextBase::hasVtableSlot(Method)) {2054if (Method->isPureVirtual())2055SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;2056else2057SPFlags |= llvm::DISubprogram::SPFlagVirtual;20582059if (CGM.getTarget().getCXXABI().isItaniumFamily()) {2060// It doesn't make sense to give a virtual destructor a vtable index,2061// since a single destructor has two entries in the vtable.2062if (!isa<CXXDestructorDecl>(Method))2063VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);2064} else {2065// Emit MS ABI vftable information. There is only one entry for the2066// deleting dtor.2067const auto *DD = dyn_cast<CXXDestructorDecl>(Method);2068GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);2069MethodVFTableLocation ML =2070CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);2071VIndex = ML.Index;20722073// CodeView only records the vftable offset in the class that introduces2074// the virtual method. This is possible because, unlike Itanium, the MS2075// C++ ABI does not include all virtual methods from non-primary bases in2076// the vtable for the most derived class. For example, if C inherits from2077// A and B, C's primary vftable will not include B's virtual methods.2078if (Method->size_overridden_methods() == 0)2079Flags |= llvm::DINode::FlagIntroducedVirtual;20802081// The 'this' adjustment accounts for both the virtual and non-virtual2082// portions of the adjustment. Presumably the debugger only uses it when2083// it knows the dynamic type of an object.2084ThisAdjustment = CGM.getCXXABI()2085.getVirtualFunctionPrologueThisAdjustment(GD)2086.getQuantity();2087}2088ContainingType = RecordTy;2089}20902091if (Method->getCanonicalDecl()->isDeleted())2092SPFlags |= llvm::DISubprogram::SPFlagDeleted;20932094if (Method->isNoReturn())2095Flags |= llvm::DINode::FlagNoReturn;20962097if (Method->isStatic())2098Flags |= llvm::DINode::FlagStaticMember;2099if (Method->isImplicit())2100Flags |= llvm::DINode::FlagArtificial;2101Flags |= getAccessFlag(Method->getAccess(), Method->getParent());2102if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {2103if (CXXC->isExplicit())2104Flags |= llvm::DINode::FlagExplicit;2105} else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {2106if (CXXC->isExplicit())2107Flags |= llvm::DINode::FlagExplicit;2108}2109if (Method->hasPrototype())2110Flags |= llvm::DINode::FlagPrototyped;2111if (Method->getRefQualifier() == RQ_LValue)2112Flags |= llvm::DINode::FlagLValueReference;2113if (Method->getRefQualifier() == RQ_RValue)2114Flags |= llvm::DINode::FlagRValueReference;2115if (!Method->isExternallyVisible())2116SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;2117if (CGM.getLangOpts().Optimize)2118SPFlags |= llvm::DISubprogram::SPFlagOptimized;21192120// In this debug mode, emit type info for a class when its constructor type2121// info is emitted.2122if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)2123if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))2124completeUnusedClass(*CD->getParent());21252126llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);2127llvm::DISubprogram *SP = DBuilder.createMethod(2128RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,2129MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,2130TParamsArray.get());21312132SPCache[Method->getCanonicalDecl()].reset(SP);21332134return SP;2135}21362137void CGDebugInfo::CollectCXXMemberFunctions(2138const CXXRecordDecl *RD, llvm::DIFile *Unit,2139SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {21402141// Since we want more than just the individual member decls if we2142// have templated functions iterate over every declaration to gather2143// the functions.2144for (const auto *I : RD->decls()) {2145const auto *Method = dyn_cast<CXXMethodDecl>(I);2146// If the member is implicit, don't add it to the member list. This avoids2147// the member being added to type units by LLVM, while still allowing it2148// to be emitted into the type declaration/reference inside the compile2149// unit.2150// Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.2151// FIXME: Handle Using(Shadow?)Decls here to create2152// DW_TAG_imported_declarations inside the class for base decls brought into2153// derived classes. GDB doesn't seem to notice/leverage these when I tried2154// it, so I'm not rushing to fix this. (GCC seems to produce them, if2155// referenced)2156if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())2157continue;21582159if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())2160continue;21612162// Reuse the existing member function declaration if it exists.2163// It may be associated with the declaration of the type & should be2164// reused as we're building the definition.2165//2166// This situation can arise in the vtable-based debug info reduction where2167// implicit members are emitted in a non-vtable TU.2168auto MI = SPCache.find(Method->getCanonicalDecl());2169EltTys.push_back(MI == SPCache.end()2170? CreateCXXMemberFunction(Method, Unit, RecordTy)2171: static_cast<llvm::Metadata *>(MI->second));2172}2173}21742175void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,2176SmallVectorImpl<llvm::Metadata *> &EltTys,2177llvm::DIType *RecordTy) {2178llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;2179CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,2180llvm::DINode::FlagZero);21812182// If we are generating CodeView debug info, we also need to emit records for2183// indirect virtual base classes.2184if (CGM.getCodeGenOpts().EmitCodeView) {2185CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,2186llvm::DINode::FlagIndirectVirtualBase);2187}2188}21892190void CGDebugInfo::CollectCXXBasesAux(2191const CXXRecordDecl *RD, llvm::DIFile *Unit,2192SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,2193const CXXRecordDecl::base_class_const_range &Bases,2194llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,2195llvm::DINode::DIFlags StartingFlags) {2196const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);2197for (const auto &BI : Bases) {2198const auto *Base =2199cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());2200if (!SeenTypes.insert(Base).second)2201continue;2202auto *BaseTy = getOrCreateType(BI.getType(), Unit);2203llvm::DINode::DIFlags BFlags = StartingFlags;2204uint64_t BaseOffset;2205uint32_t VBPtrOffset = 0;22062207if (BI.isVirtual()) {2208if (CGM.getTarget().getCXXABI().isItaniumFamily()) {2209// virtual base offset offset is -ve. The code generator emits dwarf2210// expression where it expects +ve number.2211BaseOffset = 0 - CGM.getItaniumVTableContext()2212.getVirtualBaseOffsetOffset(RD, Base)2213.getQuantity();2214} else {2215// In the MS ABI, store the vbtable offset, which is analogous to the2216// vbase offset offset in Itanium.2217BaseOffset =22184 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);2219VBPtrOffset = CGM.getContext()2220.getASTRecordLayout(RD)2221.getVBPtrOffset()2222.getQuantity();2223}2224BFlags |= llvm::DINode::FlagVirtual;2225} else2226BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));2227// FIXME: Inconsistent units for BaseOffset. It is in bytes when2228// BI->isVirtual() and bits when not.22292230BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);2231llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,2232VBPtrOffset, BFlags);2233EltTys.push_back(DTy);2234}2235}22362237llvm::DINodeArray2238CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,2239llvm::DIFile *Unit) {2240if (!OArgs)2241return llvm::DINodeArray();2242TemplateArgs &Args = *OArgs;2243SmallVector<llvm::Metadata *, 16> TemplateParams;2244for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {2245const TemplateArgument &TA = Args.Args[i];2246StringRef Name;2247const bool defaultParameter = TA.getIsDefaulted();2248if (Args.TList)2249Name = Args.TList->getParam(i)->getName();22502251switch (TA.getKind()) {2252case TemplateArgument::Type: {2253llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);2254TemplateParams.push_back(DBuilder.createTemplateTypeParameter(2255TheCU, Name, TTy, defaultParameter));22562257} break;2258case TemplateArgument::Integral: {2259llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);2260TemplateParams.push_back(DBuilder.createTemplateValueParameter(2261TheCU, Name, TTy, defaultParameter,2262llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));2263} break;2264case TemplateArgument::Declaration: {2265const ValueDecl *D = TA.getAsDecl();2266QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());2267llvm::DIType *TTy = getOrCreateType(T, Unit);2268llvm::Constant *V = nullptr;2269// Skip retrieve the value if that template parameter has cuda device2270// attribute, i.e. that value is not available at the host side.2271if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||2272!D->hasAttr<CUDADeviceAttr>()) {2273// Variable pointer template parameters have a value that is the address2274// of the variable.2275if (const auto *VD = dyn_cast<VarDecl>(D))2276V = CGM.GetAddrOfGlobalVar(VD);2277// Member function pointers have special support for building them,2278// though this is currently unsupported in LLVM CodeGen.2279else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);2280MD && MD->isImplicitObjectMemberFunction())2281V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);2282else if (const auto *FD = dyn_cast<FunctionDecl>(D))2283V = CGM.GetAddrOfFunction(FD);2284// Member data pointers have special handling too to compute the fixed2285// offset within the object.2286else if (const auto *MPT =2287dyn_cast<MemberPointerType>(T.getTypePtr())) {2288// These five lines (& possibly the above member function pointer2289// handling) might be able to be refactored to use similar code in2290// CodeGenModule::getMemberPointerConstant2291uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);2292CharUnits chars =2293CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);2294V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);2295} else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {2296V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();2297} else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {2298if (T->isRecordType())2299V = ConstantEmitter(CGM).emitAbstract(2300SourceLocation(), TPO->getValue(), TPO->getType());2301else2302V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();2303}2304assert(V && "Failed to find template parameter pointer");2305V = V->stripPointerCasts();2306}2307TemplateParams.push_back(DBuilder.createTemplateValueParameter(2308TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));2309} break;2310case TemplateArgument::NullPtr: {2311QualType T = TA.getNullPtrType();2312llvm::DIType *TTy = getOrCreateType(T, Unit);2313llvm::Constant *V = nullptr;2314// Special case member data pointer null values since they're actually -12315// instead of zero.2316if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))2317// But treat member function pointers as simple zero integers because2318// it's easier than having a special case in LLVM's CodeGen. If LLVM2319// CodeGen grows handling for values of non-null member function2320// pointers then perhaps we could remove this special case and rely on2321// EmitNullMemberPointer for member function pointers.2322if (MPT->isMemberDataPointer())2323V = CGM.getCXXABI().EmitNullMemberPointer(MPT);2324if (!V)2325V = llvm::ConstantInt::get(CGM.Int8Ty, 0);2326TemplateParams.push_back(DBuilder.createTemplateValueParameter(2327TheCU, Name, TTy, defaultParameter, V));2328} break;2329case TemplateArgument::StructuralValue: {2330QualType T = TA.getStructuralValueType();2331llvm::DIType *TTy = getOrCreateType(T, Unit);2332llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(2333SourceLocation(), TA.getAsStructuralValue(), T);2334TemplateParams.push_back(DBuilder.createTemplateValueParameter(2335TheCU, Name, TTy, defaultParameter, V));2336} break;2337case TemplateArgument::Template: {2338std::string QualName;2339llvm::raw_string_ostream OS(QualName);2340TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName(2341OS, getPrintingPolicy());2342TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(2343TheCU, Name, nullptr, OS.str(), defaultParameter));2344break;2345}2346case TemplateArgument::Pack:2347TemplateParams.push_back(DBuilder.createTemplateParameterPack(2348TheCU, Name, nullptr,2349CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));2350break;2351case TemplateArgument::Expression: {2352const Expr *E = TA.getAsExpr();2353QualType T = E->getType();2354if (E->isGLValue())2355T = CGM.getContext().getLValueReferenceType(T);2356llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);2357assert(V && "Expression in template argument isn't constant");2358llvm::DIType *TTy = getOrCreateType(T, Unit);2359TemplateParams.push_back(DBuilder.createTemplateValueParameter(2360TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));2361} break;2362// And the following should never occur:2363case TemplateArgument::TemplateExpansion:2364case TemplateArgument::Null:2365llvm_unreachable(2366"These argument types shouldn't exist in concrete types");2367}2368}2369return DBuilder.getOrCreateArray(TemplateParams);2370}23712372std::optional<CGDebugInfo::TemplateArgs>2373CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {2374if (FD->getTemplatedKind() ==2375FunctionDecl::TK_FunctionTemplateSpecialization) {2376const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()2377->getTemplate()2378->getTemplateParameters();2379return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};2380}2381return std::nullopt;2382}2383std::optional<CGDebugInfo::TemplateArgs>2384CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {2385// Always get the full list of parameters, not just the ones from the2386// specialization. A partial specialization may have fewer parameters than2387// there are arguments.2388auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);2389if (!TS)2390return std::nullopt;2391VarTemplateDecl *T = TS->getSpecializedTemplate();2392const TemplateParameterList *TList = T->getTemplateParameters();2393auto TA = TS->getTemplateArgs().asArray();2394return {{TList, TA}};2395}2396std::optional<CGDebugInfo::TemplateArgs>2397CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {2398if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {2399// Always get the full list of parameters, not just the ones from the2400// specialization. A partial specialization may have fewer parameters than2401// there are arguments.2402TemplateParameterList *TPList =2403TSpecial->getSpecializedTemplate()->getTemplateParameters();2404const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();2405return {{TPList, TAList.asArray()}};2406}2407return std::nullopt;2408}24092410llvm::DINodeArray2411CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,2412llvm::DIFile *Unit) {2413return CollectTemplateParams(GetTemplateArgs(FD), Unit);2414}24152416llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,2417llvm::DIFile *Unit) {2418return CollectTemplateParams(GetTemplateArgs(VL), Unit);2419}24202421llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,2422llvm::DIFile *Unit) {2423return CollectTemplateParams(GetTemplateArgs(RD), Unit);2424}24252426llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {2427if (!D->hasAttr<BTFDeclTagAttr>())2428return nullptr;24292430SmallVector<llvm::Metadata *, 4> Annotations;2431for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {2432llvm::Metadata *Ops[2] = {2433llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),2434llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};2435Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));2436}2437return DBuilder.getOrCreateArray(Annotations);2438}24392440llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {2441if (VTablePtrType)2442return VTablePtrType;24432444ASTContext &Context = CGM.getContext();24452446/* Function type */2447llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);2448llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);2449llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);2450unsigned Size = Context.getTypeSize(Context.VoidPtrTy);2451unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();2452std::optional<unsigned> DWARFAddressSpace =2453CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);24542455llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(2456SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");2457VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);2458return VTablePtrType;2459}24602461StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {2462// Copy the gdb compatible name on the side and use its reference.2463return internString("_vptr$", RD->getNameAsString());2464}24652466StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,2467DynamicInitKind StubKind,2468llvm::Function *InitFn) {2469// If we're not emitting codeview, use the mangled name. For Itanium, this is2470// arbitrary.2471if (!CGM.getCodeGenOpts().EmitCodeView ||2472StubKind == DynamicInitKind::GlobalArrayDestructor)2473return InitFn->getName();24742475// Print the normal qualified name for the variable, then break off the last2476// NNS, and add the appropriate other text. Clang always prints the global2477// variable name without template arguments, so we can use rsplit("::") and2478// then recombine the pieces.2479SmallString<128> QualifiedGV;2480StringRef Quals;2481StringRef GVName;2482{2483llvm::raw_svector_ostream OS(QualifiedGV);2484VD->printQualifiedName(OS, getPrintingPolicy());2485std::tie(Quals, GVName) = OS.str().rsplit("::");2486if (GVName.empty())2487std::swap(Quals, GVName);2488}24892490SmallString<128> InitName;2491llvm::raw_svector_ostream OS(InitName);2492if (!Quals.empty())2493OS << Quals << "::";24942495switch (StubKind) {2496case DynamicInitKind::NoStub:2497case DynamicInitKind::GlobalArrayDestructor:2498llvm_unreachable("not an initializer");2499case DynamicInitKind::Initializer:2500OS << "`dynamic initializer for '";2501break;2502case DynamicInitKind::AtExit:2503OS << "`dynamic atexit destructor for '";2504break;2505}25062507OS << GVName;25082509// Add any template specialization args.2510if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {2511printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),2512getPrintingPolicy());2513}25142515OS << '\'';25162517return internString(OS.str());2518}25192520void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,2521SmallVectorImpl<llvm::Metadata *> &EltTys) {2522// If this class is not dynamic then there is not any vtable info to collect.2523if (!RD->isDynamicClass())2524return;25252526// Don't emit any vtable shape or vptr info if this class doesn't have an2527// extendable vfptr. This can happen if the class doesn't have virtual2528// methods, or in the MS ABI if those virtual methods only come from virtually2529// inherited bases.2530const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);2531if (!RL.hasExtendableVFPtr())2532return;25332534// CodeView needs to know how large the vtable of every dynamic class is, so2535// emit a special named pointer type into the element list. The vptr type2536// points to this type as well.2537llvm::DIType *VPtrTy = nullptr;2538bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&2539CGM.getTarget().getCXXABI().isMicrosoft();2540if (NeedVTableShape) {2541uint64_t PtrWidth =2542CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);2543const VTableLayout &VFTLayout =2544CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());2545unsigned VSlotCount =2546VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;2547unsigned VTableWidth = PtrWidth * VSlotCount;2548unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();2549std::optional<unsigned> DWARFAddressSpace =2550CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);25512552// Create a very wide void* type and insert it directly in the element list.2553llvm::DIType *VTableType = DBuilder.createPointerType(2554nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");2555EltTys.push_back(VTableType);25562557// The vptr is a pointer to this special vtable type.2558VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);2559}25602561// If there is a primary base then the artificial vptr member lives there.2562if (RL.getPrimaryBase())2563return;25642565if (!VPtrTy)2566VPtrTy = getOrCreateVTablePtrType(Unit);25672568unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);2569llvm::DIType *VPtrMember =2570DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,2571llvm::DINode::FlagArtificial, VPtrTy);2572EltTys.push_back(VPtrMember);2573}25742575llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,2576SourceLocation Loc) {2577assert(CGM.getCodeGenOpts().hasReducedDebugInfo());2578llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));2579return T;2580}25812582llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,2583SourceLocation Loc) {2584return getOrCreateStandaloneType(D, Loc);2585}25862587llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,2588SourceLocation Loc) {2589assert(CGM.getCodeGenOpts().hasReducedDebugInfo());2590assert(!D.isNull() && "null type");2591llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));2592assert(T && "could not create debug info for type");25932594RetainedTypes.push_back(D.getAsOpaquePtr());2595return T;2596}25972598void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,2599QualType AllocatedTy,2600SourceLocation Loc) {2601if (CGM.getCodeGenOpts().getDebugInfo() <=2602llvm::codegenoptions::DebugLineTablesOnly)2603return;2604llvm::MDNode *node;2605if (AllocatedTy->isVoidType())2606node = llvm::MDNode::get(CGM.getLLVMContext(), std::nullopt);2607else2608node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));26092610CI->setMetadata("heapallocsite", node);2611}26122613void CGDebugInfo::completeType(const EnumDecl *ED) {2614if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)2615return;2616QualType Ty = CGM.getContext().getEnumType(ED);2617void *TyPtr = Ty.getAsOpaquePtr();2618auto I = TypeCache.find(TyPtr);2619if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())2620return;2621llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());2622assert(!Res->isForwardDecl());2623TypeCache[TyPtr].reset(Res);2624}26252626void CGDebugInfo::completeType(const RecordDecl *RD) {2627if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||2628!CGM.getLangOpts().CPlusPlus)2629completeRequiredType(RD);2630}26312632/// Return true if the class or any of its methods are marked dllimport.2633static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {2634if (RD->hasAttr<DLLImportAttr>())2635return true;2636for (const CXXMethodDecl *MD : RD->methods())2637if (MD->hasAttr<DLLImportAttr>())2638return true;2639return false;2640}26412642/// Does a type definition exist in an imported clang module?2643static bool isDefinedInClangModule(const RecordDecl *RD) {2644// Only definitions that where imported from an AST file come from a module.2645if (!RD || !RD->isFromASTFile())2646return false;2647// Anonymous entities cannot be addressed. Treat them as not from module.2648if (!RD->isExternallyVisible() && RD->getName().empty())2649return false;2650if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {2651if (!CXXDecl->isCompleteDefinition())2652return false;2653// Check wether RD is a template.2654auto TemplateKind = CXXDecl->getTemplateSpecializationKind();2655if (TemplateKind != TSK_Undeclared) {2656// Unfortunately getOwningModule() isn't accurate enough to find the2657// owning module of a ClassTemplateSpecializationDecl that is inside a2658// namespace spanning multiple modules.2659bool Explicit = false;2660if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))2661Explicit = TD->isExplicitInstantiationOrSpecialization();2662if (!Explicit && CXXDecl->getEnclosingNamespaceContext())2663return false;2664// This is a template, check the origin of the first member.2665if (CXXDecl->field_begin() == CXXDecl->field_end())2666return TemplateKind == TSK_ExplicitInstantiationDeclaration;2667if (!CXXDecl->field_begin()->isFromASTFile())2668return false;2669}2670}2671return true;2672}26732674void CGDebugInfo::completeClassData(const RecordDecl *RD) {2675if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))2676if (CXXRD->isDynamicClass() &&2677CGM.getVTableLinkage(CXXRD) ==2678llvm::GlobalValue::AvailableExternallyLinkage &&2679!isClassOrMethodDLLImport(CXXRD))2680return;26812682if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))2683return;26842685completeClass(RD);2686}26872688void CGDebugInfo::completeClass(const RecordDecl *RD) {2689if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)2690return;2691QualType Ty = CGM.getContext().getRecordType(RD);2692void *TyPtr = Ty.getAsOpaquePtr();2693auto I = TypeCache.find(TyPtr);2694if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())2695return;26962697// We want the canonical definition of the structure to not2698// be the typedef. Since that would lead to circular typedef2699// metadata.2700auto [Res, PrefRes] = CreateTypeDefinition(Ty->castAs<RecordType>());2701assert(!Res->isForwardDecl());2702TypeCache[TyPtr].reset(Res);2703}27042705static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,2706CXXRecordDecl::method_iterator End) {2707for (CXXMethodDecl *MD : llvm::make_range(I, End))2708if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())2709if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&2710!MD->getMemberSpecializationInfo()->isExplicitSpecialization())2711return true;2712return false;2713}27142715static bool canUseCtorHoming(const CXXRecordDecl *RD) {2716// Constructor homing can be used for classes that cannnot be constructed2717// without emitting code for one of their constructors. This is classes that2718// don't have trivial or constexpr constructors, or can be created from2719// aggregate initialization. Also skip lambda objects because they don't call2720// constructors.27212722// Skip this optimization if the class or any of its methods are marked2723// dllimport.2724if (isClassOrMethodDLLImport(RD))2725return false;27262727if (RD->isLambda() || RD->isAggregate() ||2728RD->hasTrivialDefaultConstructor() ||2729RD->hasConstexprNonCopyMoveConstructor())2730return false;27312732for (const CXXConstructorDecl *Ctor : RD->ctors()) {2733if (Ctor->isCopyOrMoveConstructor())2734continue;2735if (!Ctor->isDeleted())2736return true;2737}2738return false;2739}27402741static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,2742bool DebugTypeExtRefs, const RecordDecl *RD,2743const LangOptions &LangOpts) {2744if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))2745return true;27462747if (auto *ES = RD->getASTContext().getExternalSource())2748if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)2749return true;27502751// Only emit forward declarations in line tables only to keep debug info size2752// small. This only applies to CodeView, since we don't emit types in DWARF2753// line tables only.2754if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)2755return true;27562757if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||2758RD->hasAttr<StandaloneDebugAttr>())2759return false;27602761if (!LangOpts.CPlusPlus)2762return false;27632764if (!RD->isCompleteDefinitionRequired())2765return true;27662767const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);27682769if (!CXXDecl)2770return false;27712772// Only emit complete debug info for a dynamic class when its vtable is2773// emitted. However, Microsoft debuggers don't resolve type information2774// across DLL boundaries, so skip this optimization if the class or any of its2775// methods are marked dllimport. This isn't a complete solution, since objects2776// without any dllimport methods can be used in one DLL and constructed in2777// another, but it is the current behavior of LimitedDebugInfo.2778if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&2779!isClassOrMethodDLLImport(CXXDecl))2780return true;27812782TemplateSpecializationKind Spec = TSK_Undeclared;2783if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))2784Spec = SD->getSpecializationKind();27852786if (Spec == TSK_ExplicitInstantiationDeclaration &&2787hasExplicitMemberDefinition(CXXDecl->method_begin(),2788CXXDecl->method_end()))2789return true;27902791// In constructor homing mode, only emit complete debug info for a class2792// when its constructor is emitted.2793if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&2794canUseCtorHoming(CXXDecl))2795return true;27962797return false;2798}27992800void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {2801if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))2802return;28032804QualType Ty = CGM.getContext().getRecordType(RD);2805llvm::DIType *T = getTypeOrNull(Ty);2806if (T && T->isForwardDecl())2807completeClassData(RD);2808}28092810llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {2811RecordDecl *RD = Ty->getDecl();2812llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));2813if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,2814CGM.getLangOpts())) {2815if (!T)2816T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));2817return T;2818}28192820auto [Def, Pref] = CreateTypeDefinition(Ty);28212822return Pref ? Pref : Def;2823}28242825llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,2826llvm::DIFile *Unit) {2827if (!RD)2828return nullptr;28292830auto const *PNA = RD->getAttr<PreferredNameAttr>();2831if (!PNA)2832return nullptr;28332834return getOrCreateType(PNA->getTypedefType(), Unit);2835}28362837std::pair<llvm::DIType *, llvm::DIType *>2838CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {2839RecordDecl *RD = Ty->getDecl();28402841// Get overall information about the record type for the debug info.2842llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());28432844// Records and classes and unions can all be recursive. To handle them, we2845// first generate a debug descriptor for the struct as a forward declaration.2846// Then (if it is a definition) we go through and get debug info for all of2847// its members. Finally, we create a descriptor for the complete type (which2848// may refer to the forward decl if the struct is recursive) and replace all2849// uses of the forward declaration with the final definition.2850llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);28512852const RecordDecl *D = RD->getDefinition();2853if (!D || !D->isCompleteDefinition())2854return {FwdDecl, nullptr};28552856if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))2857CollectContainingType(CXXDecl, FwdDecl);28582859// Push the struct on region stack.2860LexicalBlockStack.emplace_back(&*FwdDecl);2861RegionMap[Ty->getDecl()].reset(FwdDecl);28622863// Convert all the elements.2864SmallVector<llvm::Metadata *, 16> EltTys;2865// what about nested types?28662867// Note: The split of CXXDecl information here is intentional, the2868// gdb tests will depend on a certain ordering at printout. The debug2869// information offsets are still correct if we merge them all together2870// though.2871const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);2872if (CXXDecl) {2873CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);2874CollectVTableInfo(CXXDecl, DefUnit, EltTys);2875}28762877// Collect data fields (including static variables and any initializers).2878CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);2879if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)2880CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);28812882LexicalBlockStack.pop_back();2883RegionMap.erase(Ty->getDecl());28842885llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);2886DBuilder.replaceArrays(FwdDecl, Elements);28872888if (FwdDecl->isTemporary())2889FwdDecl =2890llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));28912892RegionMap[Ty->getDecl()].reset(FwdDecl);28932894if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)2895if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))2896return {FwdDecl, PrefDI};28972898return {FwdDecl, nullptr};2899}29002901llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,2902llvm::DIFile *Unit) {2903// Ignore protocols.2904return getOrCreateType(Ty->getBaseType(), Unit);2905}29062907llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,2908llvm::DIFile *Unit) {2909// Ignore protocols.2910SourceLocation Loc = Ty->getDecl()->getLocation();29112912// Use Typedefs to represent ObjCTypeParamType.2913return DBuilder.createTypedef(2914getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),2915Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),2916getDeclContextDescriptor(Ty->getDecl()));2917}29182919/// \return true if Getter has the default name for the property PD.2920static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,2921const ObjCMethodDecl *Getter) {2922assert(PD);2923if (!Getter)2924return true;29252926assert(Getter->getDeclName().isObjCZeroArgSelector());2927return PD->getName() ==2928Getter->getDeclName().getObjCSelector().getNameForSlot(0);2929}29302931/// \return true if Setter has the default name for the property PD.2932static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,2933const ObjCMethodDecl *Setter) {2934assert(PD);2935if (!Setter)2936return true;29372938assert(Setter->getDeclName().isObjCOneArgSelector());2939return SelectorTable::constructSetterName(PD->getName()) ==2940Setter->getDeclName().getObjCSelector().getNameForSlot(0);2941}29422943llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,2944llvm::DIFile *Unit) {2945ObjCInterfaceDecl *ID = Ty->getDecl();2946if (!ID)2947return nullptr;29482949// Return a forward declaration if this type was imported from a clang module,2950// and this is not the compile unit with the implementation of the type (which2951// may contain hidden ivars).2952if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&2953!ID->getImplementation())2954return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,2955ID->getName(),2956getDeclContextDescriptor(ID), Unit, 0);29572958// Get overall information about the record type for the debug info.2959llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());2960unsigned Line = getLineNumber(ID->getLocation());2961auto RuntimeLang =2962static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());29632964// If this is just a forward declaration return a special forward-declaration2965// debug type since we won't be able to lay out the entire type.2966ObjCInterfaceDecl *Def = ID->getDefinition();2967if (!Def || !Def->getImplementation()) {2968llvm::DIScope *Mod = getParentModuleOrNull(ID);2969llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(2970llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,2971DefUnit, Line, RuntimeLang);2972ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));2973return FwdDecl;2974}29752976return CreateTypeDefinition(Ty, Unit);2977}29782979llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,2980bool CreateSkeletonCU) {2981// Use the Module pointer as the key into the cache. This is a2982// nullptr if the "Module" is a PCH, which is safe because we don't2983// support chained PCH debug info, so there can only be a single PCH.2984const Module *M = Mod.getModuleOrNull();2985auto ModRef = ModuleCache.find(M);2986if (ModRef != ModuleCache.end())2987return cast<llvm::DIModule>(ModRef->second);29882989// Macro definitions that were defined with "-D" on the command line.2990SmallString<128> ConfigMacros;2991{2992llvm::raw_svector_ostream OS(ConfigMacros);2993const auto &PPOpts = CGM.getPreprocessorOpts();2994unsigned I = 0;2995// Translate the macro definitions back into a command line.2996for (auto &M : PPOpts.Macros) {2997if (++I > 1)2998OS << " ";2999const std::string &Macro = M.first;3000bool Undef = M.second;3001OS << "\"-" << (Undef ? 'U' : 'D');3002for (char c : Macro)3003switch (c) {3004case '\\':3005OS << "\\\\";3006break;3007case '"':3008OS << "\\\"";3009break;3010default:3011OS << c;3012}3013OS << '\"';3014}3015}30163017bool IsRootModule = M ? !M->Parent : true;3018// When a module name is specified as -fmodule-name, that module gets a3019// clang::Module object, but it won't actually be built or imported; it will3020// be textual.3021if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)3022assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&3023"clang module without ASTFile must be specified by -fmodule-name");30243025// Return a StringRef to the remapped Path.3026auto RemapPath = [this](StringRef Path) -> std::string {3027std::string Remapped = remapDIPath(Path);3028StringRef Relative(Remapped);3029StringRef CompDir = TheCU->getDirectory();3030if (Relative.consume_front(CompDir))3031Relative.consume_front(llvm::sys::path::get_separator());30323033return Relative.str();3034};30353036if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {3037// PCH files don't have a signature field in the control block,3038// but LLVM detects skeleton CUs by looking for a non-zero DWO id.3039// We use the lower 64 bits for debug info.30403041uint64_t Signature = 0;3042if (const auto &ModSig = Mod.getSignature())3043Signature = ModSig.truncatedValue();3044else3045Signature = ~1ULL;30463047llvm::DIBuilder DIB(CGM.getModule());3048SmallString<0> PCM;3049if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {3050if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd)3051PCM = getCurrentDirname();3052else3053PCM = Mod.getPath();3054}3055llvm::sys::path::append(PCM, Mod.getASTFile());3056DIB.createCompileUnit(3057TheCU->getSourceLanguage(),3058// TODO: Support "Source" from external AST providers?3059DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),3060TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),3061llvm::DICompileUnit::FullDebug, Signature);3062DIB.finalize();3063}30643065llvm::DIModule *Parent =3066IsRootModule ? nullptr3067: getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),3068CreateSkeletonCU);3069std::string IncludePath = Mod.getPath().str();3070llvm::DIModule *DIMod =3071DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,3072RemapPath(IncludePath));3073ModuleCache[M].reset(DIMod);3074return DIMod;3075}30763077llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,3078llvm::DIFile *Unit) {3079ObjCInterfaceDecl *ID = Ty->getDecl();3080llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());3081unsigned Line = getLineNumber(ID->getLocation());3082unsigned RuntimeLang = TheCU->getSourceLanguage();30833084// Bit size, align and offset of the type.3085uint64_t Size = CGM.getContext().getTypeSize(Ty);3086auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());30873088llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;3089if (ID->getImplementation())3090Flags |= llvm::DINode::FlagObjcClassComplete;30913092llvm::DIScope *Mod = getParentModuleOrNull(ID);3093llvm::DICompositeType *RealDecl = DBuilder.createStructType(3094Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,3095nullptr, llvm::DINodeArray(), RuntimeLang);30963097QualType QTy(Ty, 0);3098TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);30993100// Push the struct on region stack.3101LexicalBlockStack.emplace_back(RealDecl);3102RegionMap[Ty->getDecl()].reset(RealDecl);31033104// Convert all the elements.3105SmallVector<llvm::Metadata *, 16> EltTys;31063107ObjCInterfaceDecl *SClass = ID->getSuperClass();3108if (SClass) {3109llvm::DIType *SClassTy =3110getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);3111if (!SClassTy)3112return nullptr;31133114llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,3115llvm::DINode::FlagZero);3116EltTys.push_back(InhTag);3117}31183119// Create entries for all of the properties.3120auto AddProperty = [&](const ObjCPropertyDecl *PD) {3121SourceLocation Loc = PD->getLocation();3122llvm::DIFile *PUnit = getOrCreateFile(Loc);3123unsigned PLine = getLineNumber(Loc);3124ObjCMethodDecl *Getter = PD->getGetterMethodDecl();3125ObjCMethodDecl *Setter = PD->getSetterMethodDecl();3126llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(3127PD->getName(), PUnit, PLine,3128hasDefaultGetterName(PD, Getter) ? ""3129: getSelectorName(PD->getGetterName()),3130hasDefaultSetterName(PD, Setter) ? ""3131: getSelectorName(PD->getSetterName()),3132PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));3133EltTys.push_back(PropertyNode);3134};3135{3136// Use 'char' for the isClassProperty bit as DenseSet requires space for3137// empty/tombstone keys in the data type (and bool is too small for that).3138typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;3139/// List of already emitted properties. Two distinct class and instance3140/// properties can share the same identifier (but not two instance3141/// properties or two class properties).3142llvm::DenseSet<IsClassAndIdent> PropertySet;3143/// Returns the IsClassAndIdent key for the given property.3144auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {3145return std::make_pair(PD->isClassProperty(), PD->getIdentifier());3146};3147for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())3148for (auto *PD : ClassExt->properties()) {3149PropertySet.insert(GetIsClassAndIdent(PD));3150AddProperty(PD);3151}3152for (const auto *PD : ID->properties()) {3153// Don't emit duplicate metadata for properties that were already in a3154// class extension.3155if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)3156continue;3157AddProperty(PD);3158}3159}31603161const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);3162unsigned FieldNo = 0;3163for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;3164Field = Field->getNextIvar(), ++FieldNo) {3165llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);3166if (!FieldTy)3167return nullptr;31683169StringRef FieldName = Field->getName();31703171// Ignore unnamed fields.3172if (FieldName.empty())3173continue;31743175// Get the location for the field.3176llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());3177unsigned FieldLine = getLineNumber(Field->getLocation());3178QualType FType = Field->getType();3179uint64_t FieldSize = 0;3180uint32_t FieldAlign = 0;31813182if (!FType->isIncompleteArrayType()) {31833184// Bit size, align and offset of the type.3185FieldSize = Field->isBitField()3186? Field->getBitWidthValue(CGM.getContext())3187: CGM.getContext().getTypeSize(FType);3188FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());3189}31903191uint64_t FieldOffset;3192if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {3193// We don't know the runtime offset of an ivar if we're using the3194// non-fragile ABI. For bitfields, use the bit offset into the first3195// byte of storage of the bitfield. For other fields, use zero.3196if (Field->isBitField()) {3197FieldOffset =3198CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);3199FieldOffset %= CGM.getContext().getCharWidth();3200} else {3201FieldOffset = 0;3202}3203} else {3204FieldOffset = RL.getFieldOffset(FieldNo);3205}32063207llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;3208if (Field->getAccessControl() == ObjCIvarDecl::Protected)3209Flags = llvm::DINode::FlagProtected;3210else if (Field->getAccessControl() == ObjCIvarDecl::Private)3211Flags = llvm::DINode::FlagPrivate;3212else if (Field->getAccessControl() == ObjCIvarDecl::Public)3213Flags = llvm::DINode::FlagPublic;32143215if (Field->isBitField())3216Flags |= llvm::DINode::FlagBitField;32173218llvm::MDNode *PropertyNode = nullptr;3219if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {3220if (ObjCPropertyImplDecl *PImpD =3221ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {3222if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {3223SourceLocation Loc = PD->getLocation();3224llvm::DIFile *PUnit = getOrCreateFile(Loc);3225unsigned PLine = getLineNumber(Loc);3226ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();3227ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();3228PropertyNode = DBuilder.createObjCProperty(3229PD->getName(), PUnit, PLine,3230hasDefaultGetterName(PD, Getter)3231? ""3232: getSelectorName(PD->getGetterName()),3233hasDefaultSetterName(PD, Setter)3234? ""3235: getSelectorName(PD->getSetterName()),3236PD->getPropertyAttributes(),3237getOrCreateType(PD->getType(), PUnit));3238}3239}3240}3241FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,3242FieldSize, FieldAlign, FieldOffset, Flags,3243FieldTy, PropertyNode);3244EltTys.push_back(FieldTy);3245}32463247llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);3248DBuilder.replaceArrays(RealDecl, Elements);32493250LexicalBlockStack.pop_back();3251return RealDecl;3252}32533254llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,3255llvm::DIFile *Unit) {3256if (Ty->isExtVectorBoolType()) {3257// Boolean ext_vector_type(N) are special because their real element type3258// (bits of bit size) is not their Clang element type (_Bool of size byte).3259// For now, we pretend the boolean vector were actually a vector of bytes3260// (where each byte represents 8 bits of the actual vector).3261// FIXME Debug info should actually represent this proper as a vector mask3262// type.3263auto &Ctx = CGM.getContext();3264uint64_t Size = CGM.getContext().getTypeSize(Ty);3265uint64_t NumVectorBytes = Size / Ctx.getCharWidth();32663267// Construct the vector of 'char' type.3268QualType CharVecTy =3269Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);3270return CreateType(CharVecTy->getAs<VectorType>(), Unit);3271}32723273llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);3274int64_t Count = Ty->getNumElements();32753276llvm::Metadata *Subscript;3277QualType QTy(Ty, 0);3278auto SizeExpr = SizeExprCache.find(QTy);3279if (SizeExpr != SizeExprCache.end())3280Subscript = DBuilder.getOrCreateSubrange(3281SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,3282nullptr /*upperBound*/, nullptr /*stride*/);3283else {3284auto *CountNode =3285llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(3286llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));3287Subscript = DBuilder.getOrCreateSubrange(3288CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,3289nullptr /*stride*/);3290}3291llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);32923293uint64_t Size = CGM.getContext().getTypeSize(Ty);3294auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());32953296return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);3297}32983299llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,3300llvm::DIFile *Unit) {3301// FIXME: Create another debug type for matrices3302// For the time being, it treats it like a nested ArrayType.33033304llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);3305uint64_t Size = CGM.getContext().getTypeSize(Ty);3306uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());33073308// Create ranges for both dimensions.3309llvm::SmallVector<llvm::Metadata *, 2> Subscripts;3310auto *ColumnCountNode =3311llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(3312llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));3313auto *RowCountNode =3314llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(3315llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));3316Subscripts.push_back(DBuilder.getOrCreateSubrange(3317ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,3318nullptr /*stride*/));3319Subscripts.push_back(DBuilder.getOrCreateSubrange(3320RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,3321nullptr /*stride*/));3322llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);3323return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);3324}33253326llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {3327uint64_t Size;3328uint32_t Align;33293330// FIXME: make getTypeAlign() aware of VLAs and incomplete array types3331if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {3332Size = 0;3333Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),3334CGM.getContext());3335} else if (Ty->isIncompleteArrayType()) {3336Size = 0;3337if (Ty->getElementType()->isIncompleteType())3338Align = 0;3339else3340Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());3341} else if (Ty->isIncompleteType()) {3342Size = 0;3343Align = 0;3344} else {3345// Size and align of the whole array, not the element type.3346Size = CGM.getContext().getTypeSize(Ty);3347Align = getTypeAlignIfRequired(Ty, CGM.getContext());3348}33493350// Add the dimensions of the array. FIXME: This loses CV qualifiers from3351// interior arrays, do we care? Why aren't nested arrays represented the3352// obvious/recursive way?3353SmallVector<llvm::Metadata *, 8> Subscripts;3354QualType EltTy(Ty, 0);3355while ((Ty = dyn_cast<ArrayType>(EltTy))) {3356// If the number of elements is known, then count is that number. Otherwise,3357// it's -1. This allows us to represent a subrange with an array of 03358// elements, like this:3359//3360// struct foo {3361// int x[0];3362// };3363int64_t Count = -1; // Count == -1 is an unbounded array.3364if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))3365Count = CAT->getZExtSize();3366else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {3367if (Expr *Size = VAT->getSizeExpr()) {3368Expr::EvalResult Result;3369if (Size->EvaluateAsInt(Result, CGM.getContext()))3370Count = Result.Val.getInt().getExtValue();3371}3372}33733374auto SizeNode = SizeExprCache.find(EltTy);3375if (SizeNode != SizeExprCache.end())3376Subscripts.push_back(DBuilder.getOrCreateSubrange(3377SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,3378nullptr /*upperBound*/, nullptr /*stride*/));3379else {3380auto *CountNode =3381llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(3382llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));3383Subscripts.push_back(DBuilder.getOrCreateSubrange(3384CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,3385nullptr /*stride*/));3386}3387EltTy = Ty->getElementType();3388}33893390llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);33913392return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),3393SubscriptArray);3394}33953396llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,3397llvm::DIFile *Unit) {3398return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,3399Ty->getPointeeType(), Unit);3400}34013402llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,3403llvm::DIFile *Unit) {3404llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;3405// DW_TAG_rvalue_reference_type was introduced in DWARF 4.3406if (CGM.getCodeGenOpts().DebugStrictDwarf &&3407CGM.getCodeGenOpts().DwarfVersion < 4)3408Tag = llvm::dwarf::DW_TAG_reference_type;34093410return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);3411}34123413llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,3414llvm::DIFile *U) {3415llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;3416uint64_t Size = 0;34173418if (!Ty->isIncompleteType()) {3419Size = CGM.getContext().getTypeSize(Ty);34203421// Set the MS inheritance model. There is no flag for the unspecified model.3422if (CGM.getTarget().getCXXABI().isMicrosoft()) {3423switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {3424case MSInheritanceModel::Single:3425Flags |= llvm::DINode::FlagSingleInheritance;3426break;3427case MSInheritanceModel::Multiple:3428Flags |= llvm::DINode::FlagMultipleInheritance;3429break;3430case MSInheritanceModel::Virtual:3431Flags |= llvm::DINode::FlagVirtualInheritance;3432break;3433case MSInheritanceModel::Unspecified:3434break;3435}3436}3437}34383439llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);3440if (Ty->isMemberDataPointerType())3441return DBuilder.createMemberPointerType(3442getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,3443Flags);34443445const FunctionProtoType *FPT =3446Ty->getPointeeType()->castAs<FunctionProtoType>();3447return DBuilder.createMemberPointerType(3448getOrCreateInstanceMethodType(3449CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),3450FPT, U),3451ClassType, Size, /*Align=*/0, Flags);3452}34533454llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {3455auto *FromTy = getOrCreateType(Ty->getValueType(), U);3456return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);3457}34583459llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {3460return getOrCreateType(Ty->getElementType(), U);3461}34623463llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {3464const EnumDecl *ED = Ty->getDecl();34653466uint64_t Size = 0;3467uint32_t Align = 0;3468if (!ED->getTypeForDecl()->isIncompleteType()) {3469Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());3470Align = getDeclAlignIfRequired(ED, CGM.getContext());3471}34723473SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);34743475bool isImportedFromModule =3476DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();34773478// If this is just a forward declaration, construct an appropriately3479// marked node and just return it.3480if (isImportedFromModule || !ED->getDefinition()) {3481// Note that it is possible for enums to be created as part of3482// their own declcontext. In this case a FwdDecl will be created3483// twice. This doesn't cause a problem because both FwdDecls are3484// entered into the ReplaceMap: finalize() will replace the first3485// FwdDecl with the second and then replace the second with3486// complete type.3487llvm::DIScope *EDContext = getDeclContextDescriptor(ED);3488llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());3489llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(3490llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));34913492unsigned Line = getLineNumber(ED->getLocation());3493StringRef EDName = ED->getName();3494llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(3495llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,34960, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);34973498ReplaceMap.emplace_back(3499std::piecewise_construct, std::make_tuple(Ty),3500std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));3501return RetTy;3502}35033504return CreateTypeDefinition(Ty);3505}35063507llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {3508const EnumDecl *ED = Ty->getDecl();3509uint64_t Size = 0;3510uint32_t Align = 0;3511if (!ED->getTypeForDecl()->isIncompleteType()) {3512Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());3513Align = getDeclAlignIfRequired(ED, CGM.getContext());3514}35153516SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);35173518SmallVector<llvm::Metadata *, 16> Enumerators;3519ED = ED->getDefinition();3520for (const auto *Enum : ED->enumerators()) {3521Enumerators.push_back(3522DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));3523}35243525// Return a CompositeType for the enum itself.3526llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);35273528llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());3529unsigned Line = getLineNumber(ED->getLocation());3530llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);3531llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);3532return DBuilder.createEnumerationType(3533EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,3534/*RunTimeLang=*/0, Identifier, ED->isScoped());3535}35363537llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,3538unsigned MType, SourceLocation LineLoc,3539StringRef Name, StringRef Value) {3540unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);3541return DBuilder.createMacro(Parent, Line, MType, Name, Value);3542}35433544llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,3545SourceLocation LineLoc,3546SourceLocation FileLoc) {3547llvm::DIFile *FName = getOrCreateFile(FileLoc);3548unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);3549return DBuilder.createTempMacroFile(Parent, Line, FName);3550}35513552llvm::DILocation *CGDebugInfo::CreateTrapFailureMessageFor(3553llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {3554// Create a debug location from `TrapLocation` that adds an artificial inline3555// frame.3556SmallString<64> FuncName(ClangTrapPrefix);35573558FuncName += "$";3559FuncName += Category;3560FuncName += "$";3561FuncName += FailureMsg;35623563llvm::DISubprogram *TrapSP =3564createInlinedTrapSubprogram(FuncName, TrapLocation->getFile());3565return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,3566/*Scope=*/TrapSP, /*InlinedAt=*/TrapLocation);3567}35683569static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {3570Qualifiers Quals;3571do {3572Qualifiers InnerQuals = T.getLocalQualifiers();3573// Qualifiers::operator+() doesn't like it if you add a Qualifier3574// that is already there.3575Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);3576Quals += InnerQuals;3577QualType LastT = T;3578switch (T->getTypeClass()) {3579default:3580return C.getQualifiedType(T.getTypePtr(), Quals);3581case Type::TemplateSpecialization: {3582const auto *Spec = cast<TemplateSpecializationType>(T);3583if (Spec->isTypeAlias())3584return C.getQualifiedType(T.getTypePtr(), Quals);3585T = Spec->desugar();3586break;3587}3588case Type::TypeOfExpr:3589T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();3590break;3591case Type::TypeOf:3592T = cast<TypeOfType>(T)->getUnmodifiedType();3593break;3594case Type::Decltype:3595T = cast<DecltypeType>(T)->getUnderlyingType();3596break;3597case Type::UnaryTransform:3598T = cast<UnaryTransformType>(T)->getUnderlyingType();3599break;3600case Type::Attributed:3601T = cast<AttributedType>(T)->getEquivalentType();3602break;3603case Type::BTFTagAttributed:3604T = cast<BTFTagAttributedType>(T)->getWrappedType();3605break;3606case Type::CountAttributed:3607T = cast<CountAttributedType>(T)->desugar();3608break;3609case Type::Elaborated:3610T = cast<ElaboratedType>(T)->getNamedType();3611break;3612case Type::Using:3613T = cast<UsingType>(T)->getUnderlyingType();3614break;3615case Type::Paren:3616T = cast<ParenType>(T)->getInnerType();3617break;3618case Type::MacroQualified:3619T = cast<MacroQualifiedType>(T)->getUnderlyingType();3620break;3621case Type::SubstTemplateTypeParm:3622T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();3623break;3624case Type::Auto:3625case Type::DeducedTemplateSpecialization: {3626QualType DT = cast<DeducedType>(T)->getDeducedType();3627assert(!DT.isNull() && "Undeduced types shouldn't reach here.");3628T = DT;3629break;3630}3631case Type::PackIndexing: {3632T = cast<PackIndexingType>(T)->getSelectedType();3633break;3634}3635case Type::Adjusted:3636case Type::Decayed:3637// Decayed and adjusted types use the adjusted type in LLVM and DWARF.3638T = cast<AdjustedType>(T)->getAdjustedType();3639break;3640}36413642assert(T != LastT && "Type unwrapping failed to unwrap!");3643(void)LastT;3644} while (true);3645}36463647llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {3648assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));3649auto It = TypeCache.find(Ty.getAsOpaquePtr());3650if (It != TypeCache.end()) {3651// Verify that the debug info still exists.3652if (llvm::Metadata *V = It->second)3653return cast<llvm::DIType>(V);3654}36553656return nullptr;3657}36583659void CGDebugInfo::completeTemplateDefinition(3660const ClassTemplateSpecializationDecl &SD) {3661completeUnusedClass(SD);3662}36633664void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {3665if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||3666D.isDynamicClass())3667return;36683669completeClassData(&D);3670// In case this type has no member function definitions being emitted, ensure3671// it is retained3672RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());3673}36743675llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {3676if (Ty.isNull())3677return nullptr;36783679llvm::TimeTraceScope TimeScope("DebugType", [&]() {3680std::string Name;3681llvm::raw_string_ostream OS(Name);3682Ty.print(OS, getPrintingPolicy());3683return Name;3684});36853686// Unwrap the type as needed for debug information.3687Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());36883689if (auto *T = getTypeOrNull(Ty))3690return T;36913692llvm::DIType *Res = CreateTypeNode(Ty, Unit);3693void *TyPtr = Ty.getAsOpaquePtr();36943695// And update the type cache.3696TypeCache[TyPtr].reset(Res);36973698return Res;3699}37003701llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {3702// A forward declaration inside a module header does not belong to the module.3703if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())3704return nullptr;3705if (DebugTypeExtRefs && D->isFromASTFile()) {3706// Record a reference to an imported clang module or precompiled header.3707auto *Reader = CGM.getContext().getExternalSource();3708auto Idx = D->getOwningModuleID();3709auto Info = Reader->getSourceDescriptor(Idx);3710if (Info)3711return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);3712} else if (ClangModuleMap) {3713// We are building a clang module or a precompiled header.3714//3715// TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies3716// and it wouldn't be necessary to specify the parent scope3717// because the type is already unique by definition (it would look3718// like the output of -fno-standalone-debug). On the other hand,3719// the parent scope helps a consumer to quickly locate the object3720// file where the type's definition is located, so it might be3721// best to make this behavior a command line or debugger tuning3722// option.3723if (Module *M = D->getOwningModule()) {3724// This is a (sub-)module.3725auto Info = ASTSourceDescriptor(*M);3726return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);3727} else {3728// This the precompiled header being built.3729return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);3730}3731}37323733return nullptr;3734}37353736llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {3737// Handle qualifiers, which recursively handles what they refer to.3738if (Ty.hasLocalQualifiers())3739return CreateQualifiedType(Ty, Unit);37403741// Work out details of type.3742switch (Ty->getTypeClass()) {3743#define TYPE(Class, Base)3744#define ABSTRACT_TYPE(Class, Base)3745#define NON_CANONICAL_TYPE(Class, Base)3746#define DEPENDENT_TYPE(Class, Base) case Type::Class:3747#include "clang/AST/TypeNodes.inc"3748llvm_unreachable("Dependent types cannot show up in debug information");37493750case Type::ExtVector:3751case Type::Vector:3752return CreateType(cast<VectorType>(Ty), Unit);3753case Type::ConstantMatrix:3754return CreateType(cast<ConstantMatrixType>(Ty), Unit);3755case Type::ObjCObjectPointer:3756return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);3757case Type::ObjCObject:3758return CreateType(cast<ObjCObjectType>(Ty), Unit);3759case Type::ObjCTypeParam:3760return CreateType(cast<ObjCTypeParamType>(Ty), Unit);3761case Type::ObjCInterface:3762return CreateType(cast<ObjCInterfaceType>(Ty), Unit);3763case Type::Builtin:3764return CreateType(cast<BuiltinType>(Ty));3765case Type::Complex:3766return CreateType(cast<ComplexType>(Ty));3767case Type::Pointer:3768return CreateType(cast<PointerType>(Ty), Unit);3769case Type::BlockPointer:3770return CreateType(cast<BlockPointerType>(Ty), Unit);3771case Type::Typedef:3772return CreateType(cast<TypedefType>(Ty), Unit);3773case Type::Record:3774return CreateType(cast<RecordType>(Ty));3775case Type::Enum:3776return CreateEnumType(cast<EnumType>(Ty));3777case Type::FunctionProto:3778case Type::FunctionNoProto:3779return CreateType(cast<FunctionType>(Ty), Unit);3780case Type::ConstantArray:3781case Type::VariableArray:3782case Type::IncompleteArray:3783case Type::ArrayParameter:3784return CreateType(cast<ArrayType>(Ty), Unit);37853786case Type::LValueReference:3787return CreateType(cast<LValueReferenceType>(Ty), Unit);3788case Type::RValueReference:3789return CreateType(cast<RValueReferenceType>(Ty), Unit);37903791case Type::MemberPointer:3792return CreateType(cast<MemberPointerType>(Ty), Unit);37933794case Type::Atomic:3795return CreateType(cast<AtomicType>(Ty), Unit);37963797case Type::BitInt:3798return CreateType(cast<BitIntType>(Ty));3799case Type::Pipe:3800return CreateType(cast<PipeType>(Ty), Unit);38013802case Type::TemplateSpecialization:3803return CreateType(cast<TemplateSpecializationType>(Ty), Unit);38043805case Type::CountAttributed:3806case Type::Auto:3807case Type::Attributed:3808case Type::BTFTagAttributed:3809case Type::Adjusted:3810case Type::Decayed:3811case Type::DeducedTemplateSpecialization:3812case Type::Elaborated:3813case Type::Using:3814case Type::Paren:3815case Type::MacroQualified:3816case Type::SubstTemplateTypeParm:3817case Type::TypeOfExpr:3818case Type::TypeOf:3819case Type::Decltype:3820case Type::PackIndexing:3821case Type::UnaryTransform:3822break;3823}38243825llvm_unreachable("type should have been unwrapped!");3826}38273828llvm::DICompositeType *3829CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {3830QualType QTy(Ty, 0);38313832auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));38333834// We may have cached a forward decl when we could have created3835// a non-forward decl. Go ahead and create a non-forward decl3836// now.3837if (T && !T->isForwardDecl())3838return T;38393840// Otherwise create the type.3841llvm::DICompositeType *Res = CreateLimitedType(Ty);38423843// Propagate members from the declaration to the definition3844// CreateType(const RecordType*) will overwrite this with the members in the3845// correct order if the full type is needed.3846DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());38473848// And update the type cache.3849TypeCache[QTy.getAsOpaquePtr()].reset(Res);3850return Res;3851}38523853// TODO: Currently used for context chains when limiting debug info.3854llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {3855RecordDecl *RD = Ty->getDecl();38563857// Get overall information about the record type for the debug info.3858StringRef RDName = getClassName(RD);3859const SourceLocation Loc = RD->getLocation();3860llvm::DIFile *DefUnit = nullptr;3861unsigned Line = 0;3862if (Loc.isValid()) {3863DefUnit = getOrCreateFile(Loc);3864Line = getLineNumber(Loc);3865}38663867llvm::DIScope *RDContext = getDeclContextDescriptor(RD);38683869// If we ended up creating the type during the context chain construction,3870// just return that.3871auto *T = cast_or_null<llvm::DICompositeType>(3872getTypeOrNull(CGM.getContext().getRecordType(RD)));3873if (T && (!T->isForwardDecl() || !RD->getDefinition()))3874return T;38753876// If this is just a forward or incomplete declaration, construct an3877// appropriately marked node and just return it.3878const RecordDecl *D = RD->getDefinition();3879if (!D || !D->isCompleteDefinition())3880return getOrCreateRecordFwdDecl(Ty, RDContext);38813882uint64_t Size = CGM.getContext().getTypeSize(Ty);3883// __attribute__((aligned)) can increase or decrease alignment *except* on a3884// struct or struct member, where it only increases alignment unless 'packed'3885// is also specified. To handle this case, the `getTypeAlignIfRequired` needs3886// to be used.3887auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());38883889SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);38903891// Explicitly record the calling convention and export symbols for C++3892// records.3893auto Flags = llvm::DINode::FlagZero;3894if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {3895if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)3896Flags |= llvm::DINode::FlagTypePassByReference;3897else3898Flags |= llvm::DINode::FlagTypePassByValue;38993900// Record if a C++ record is non-trivial type.3901if (!CXXRD->isTrivial())3902Flags |= llvm::DINode::FlagNonTrivial;39033904// Record exports it symbols to the containing structure.3905if (CXXRD->isAnonymousStructOrUnion())3906Flags |= llvm::DINode::FlagExportSymbols;39073908Flags |= getAccessFlag(CXXRD->getAccess(),3909dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));3910}39113912llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);3913llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(3914getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,3915Flags, Identifier, Annotations);39163917// Elements of composite types usually have back to the type, creating3918// uniquing cycles. Distinct nodes are more efficient.3919switch (RealDecl->getTag()) {3920default:3921llvm_unreachable("invalid composite type tag");39223923case llvm::dwarf::DW_TAG_array_type:3924case llvm::dwarf::DW_TAG_enumeration_type:3925// Array elements and most enumeration elements don't have back references,3926// so they don't tend to be involved in uniquing cycles and there is some3927// chance of merging them when linking together two modules. Only make3928// them distinct if they are ODR-uniqued.3929if (Identifier.empty())3930break;3931[[fallthrough]];39323933case llvm::dwarf::DW_TAG_structure_type:3934case llvm::dwarf::DW_TAG_union_type:3935case llvm::dwarf::DW_TAG_class_type:3936// Immediately resolve to a distinct node.3937RealDecl =3938llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));3939break;3940}39413942RegionMap[Ty->getDecl()].reset(RealDecl);3943TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);39443945if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))3946DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),3947CollectCXXTemplateParams(TSpecial, DefUnit));3948return RealDecl;3949}39503951void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,3952llvm::DICompositeType *RealDecl) {3953// A class's primary base or the class itself contains the vtable.3954llvm::DIType *ContainingType = nullptr;3955const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);3956if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {3957// Seek non-virtual primary base root.3958while (true) {3959const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);3960const CXXRecordDecl *PBT = BRL.getPrimaryBase();3961if (PBT && !BRL.isPrimaryBaseVirtual())3962PBase = PBT;3963else3964break;3965}3966ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),3967getOrCreateFile(RD->getLocation()));3968} else if (RD->isDynamicClass())3969ContainingType = RealDecl;39703971DBuilder.replaceVTableHolder(RealDecl, ContainingType);3972}39733974llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,3975StringRef Name, uint64_t *Offset) {3976llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);3977uint64_t FieldSize = CGM.getContext().getTypeSize(FType);3978auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());3979llvm::DIType *Ty =3980DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,3981*Offset, llvm::DINode::FlagZero, FieldTy);3982*Offset += FieldSize;3983return Ty;3984}39853986void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,3987StringRef &Name,3988StringRef &LinkageName,3989llvm::DIScope *&FDContext,3990llvm::DINodeArray &TParamsArray,3991llvm::DINode::DIFlags &Flags) {3992const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());3993Name = getFunctionName(FD);3994// Use mangled name as linkage name for C/C++ functions.3995if (FD->getType()->getAs<FunctionProtoType>())3996LinkageName = CGM.getMangledName(GD);3997if (FD->hasPrototype())3998Flags |= llvm::DINode::FlagPrototyped;3999// No need to replicate the linkage name if it isn't different from the4000// subprogram name, no need to have it at all unless coverage is enabled or4001// debug is set to more than just line tables or extra debug info is needed.4002if (LinkageName == Name ||4003(CGM.getCodeGenOpts().CoverageNotesFile.empty() &&4004CGM.getCodeGenOpts().CoverageDataFile.empty() &&4005!CGM.getCodeGenOpts().DebugInfoForProfiling &&4006!CGM.getCodeGenOpts().PseudoProbeForProfiling &&4007DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))4008LinkageName = StringRef();40094010// Emit the function scope in line tables only mode (if CodeView) to4011// differentiate between function names.4012if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||4013(DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&4014CGM.getCodeGenOpts().EmitCodeView)) {4015if (const NamespaceDecl *NSDecl =4016dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))4017FDContext = getOrCreateNamespace(NSDecl);4018else if (const RecordDecl *RDecl =4019dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {4020llvm::DIScope *Mod = getParentModuleOrNull(RDecl);4021FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);4022}4023}4024if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {4025// Check if it is a noreturn-marked function4026if (FD->isNoReturn())4027Flags |= llvm::DINode::FlagNoReturn;4028// Collect template parameters.4029TParamsArray = CollectFunctionTemplateParams(FD, Unit);4030}4031}40324033void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,4034unsigned &LineNo, QualType &T,4035StringRef &Name, StringRef &LinkageName,4036llvm::MDTuple *&TemplateParameters,4037llvm::DIScope *&VDContext) {4038Unit = getOrCreateFile(VD->getLocation());4039LineNo = getLineNumber(VD->getLocation());40404041setLocation(VD->getLocation());40424043T = VD->getType();4044if (T->isIncompleteArrayType()) {4045// CodeGen turns int[] into int[1] so we'll do the same here.4046llvm::APInt ConstVal(32, 1);4047QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();40484049T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,4050ArraySizeModifier::Normal, 0);4051}40524053Name = VD->getName();4054if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&4055!isa<ObjCMethodDecl>(VD->getDeclContext()))4056LinkageName = CGM.getMangledName(VD);4057if (LinkageName == Name)4058LinkageName = StringRef();40594060if (isa<VarTemplateSpecializationDecl>(VD)) {4061llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);4062TemplateParameters = parameterNodes.get();4063} else {4064TemplateParameters = nullptr;4065}40664067// Since we emit declarations (DW_AT_members) for static members, place the4068// definition of those static members in the namespace they were declared in4069// in the source code (the lexical decl context).4070// FIXME: Generalize this for even non-member global variables where the4071// declaration and definition may have different lexical decl contexts, once4072// we have support for emitting declarations of (non-member) global variables.4073const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()4074: VD->getDeclContext();4075// When a record type contains an in-line initialization of a static data4076// member, and the record type is marked as __declspec(dllexport), an implicit4077// definition of the member will be created in the record context. DWARF4078// doesn't seem to have a nice way to describe this in a form that consumers4079// are likely to understand, so fake the "normal" situation of a definition4080// outside the class by putting it in the global scope.4081if (DC->isRecord())4082DC = CGM.getContext().getTranslationUnitDecl();40834084llvm::DIScope *Mod = getParentModuleOrNull(VD);4085VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);4086}40874088llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,4089bool Stub) {4090llvm::DINodeArray TParamsArray;4091StringRef Name, LinkageName;4092llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;4093llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;4094SourceLocation Loc = GD.getDecl()->getLocation();4095llvm::DIFile *Unit = getOrCreateFile(Loc);4096llvm::DIScope *DContext = Unit;4097unsigned Line = getLineNumber(Loc);4098collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,4099Flags);4100auto *FD = cast<FunctionDecl>(GD.getDecl());41014102// Build function type.4103SmallVector<QualType, 16> ArgTypes;4104for (const ParmVarDecl *Parm : FD->parameters())4105ArgTypes.push_back(Parm->getType());41064107CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();4108QualType FnType = CGM.getContext().getFunctionType(4109FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));4110if (!FD->isExternallyVisible())4111SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;4112if (CGM.getLangOpts().Optimize)4113SPFlags |= llvm::DISubprogram::SPFlagOptimized;41144115if (Stub) {4116Flags |= getCallSiteRelatedAttrs();4117SPFlags |= llvm::DISubprogram::SPFlagDefinition;4118return DBuilder.createFunction(4119DContext, Name, LinkageName, Unit, Line,4120getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,4121TParamsArray.get(), getFunctionDeclaration(FD));4122}41234124llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(4125DContext, Name, LinkageName, Unit, Line,4126getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,4127TParamsArray.get(), getFunctionDeclaration(FD));4128const FunctionDecl *CanonDecl = FD->getCanonicalDecl();4129FwdDeclReplaceMap.emplace_back(std::piecewise_construct,4130std::make_tuple(CanonDecl),4131std::make_tuple(SP));4132return SP;4133}41344135llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {4136return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);4137}41384139llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {4140return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);4141}41424143llvm::DIGlobalVariable *4144CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {4145QualType T;4146StringRef Name, LinkageName;4147SourceLocation Loc = VD->getLocation();4148llvm::DIFile *Unit = getOrCreateFile(Loc);4149llvm::DIScope *DContext = Unit;4150unsigned Line = getLineNumber(Loc);4151llvm::MDTuple *TemplateParameters = nullptr;41524153collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,4154DContext);4155auto Align = getDeclAlignIfRequired(VD, CGM.getContext());4156auto *GV = DBuilder.createTempGlobalVariableFwdDecl(4157DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),4158!VD->isExternallyVisible(), nullptr, TemplateParameters, Align);4159FwdDeclReplaceMap.emplace_back(4160std::piecewise_construct,4161std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),4162std::make_tuple(static_cast<llvm::Metadata *>(GV)));4163return GV;4164}41654166llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {4167// We only need a declaration (not a definition) of the type - so use whatever4168// we would otherwise do to get a type for a pointee. (forward declarations in4169// limited debug info, full definitions (if the type definition is available)4170// in unlimited debug info)4171if (const auto *TD = dyn_cast<TypeDecl>(D))4172return getOrCreateType(CGM.getContext().getTypeDeclType(TD),4173getOrCreateFile(TD->getLocation()));4174auto I = DeclCache.find(D->getCanonicalDecl());41754176if (I != DeclCache.end()) {4177auto N = I->second;4178if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))4179return GVE->getVariable();4180return cast<llvm::DINode>(N);4181}41824183// Search imported declaration cache if it is already defined4184// as imported declaration.4185auto IE = ImportedDeclCache.find(D->getCanonicalDecl());41864187if (IE != ImportedDeclCache.end()) {4188auto N = IE->second;4189if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))4190return cast<llvm::DINode>(GVE);4191return dyn_cast_or_null<llvm::DINode>(N);4192}41934194// No definition for now. Emit a forward definition that might be4195// merged with a potential upcoming definition.4196if (const auto *FD = dyn_cast<FunctionDecl>(D))4197return getFunctionForwardDeclaration(FD);4198else if (const auto *VD = dyn_cast<VarDecl>(D))4199return getGlobalVariableForwardDeclaration(VD);42004201return nullptr;4202}42034204llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {4205if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)4206return nullptr;42074208const auto *FD = dyn_cast<FunctionDecl>(D);4209if (!FD)4210return nullptr;42114212// Setup context.4213auto *S = getDeclContextDescriptor(D);42144215auto MI = SPCache.find(FD->getCanonicalDecl());4216if (MI == SPCache.end()) {4217if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {4218return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),4219cast<llvm::DICompositeType>(S));4220}4221}4222if (MI != SPCache.end()) {4223auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);4224if (SP && !SP->isDefinition())4225return SP;4226}42274228for (auto *NextFD : FD->redecls()) {4229auto MI = SPCache.find(NextFD->getCanonicalDecl());4230if (MI != SPCache.end()) {4231auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);4232if (SP && !SP->isDefinition())4233return SP;4234}4235}4236return nullptr;4237}42384239llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(4240const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,4241llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {4242if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)4243return nullptr;42444245const auto *OMD = dyn_cast<ObjCMethodDecl>(D);4246if (!OMD)4247return nullptr;42484249if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())4250return nullptr;42514252if (OMD->isDirectMethod())4253SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;42544255// Starting with DWARF V5 method declarations are emitted as children of4256// the interface type.4257auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());4258if (!ID)4259ID = OMD->getClassInterface();4260if (!ID)4261return nullptr;4262QualType QTy(ID->getTypeForDecl(), 0);4263auto It = TypeCache.find(QTy.getAsOpaquePtr());4264if (It == TypeCache.end())4265return nullptr;4266auto *InterfaceType = cast<llvm::DICompositeType>(It->second);4267llvm::DISubprogram *FD = DBuilder.createFunction(4268InterfaceType, getObjCMethodName(OMD), StringRef(),4269InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);4270DBuilder.finalizeSubprogram(FD);4271ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});4272return FD;4273}42744275// getOrCreateFunctionType - Construct type. If it is a c++ method, include4276// implicit parameter "this".4277llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,4278QualType FnType,4279llvm::DIFile *F) {4280// In CodeView, we emit the function types in line tables only because the4281// only way to distinguish between functions is by display name and type.4282if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&4283!CGM.getCodeGenOpts().EmitCodeView))4284// Create fake but valid subroutine type. Otherwise -verify would fail, and4285// subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.4286return DBuilder.createSubroutineType(4287DBuilder.getOrCreateTypeArray(std::nullopt));42884289if (const auto *Method = dyn_cast<CXXMethodDecl>(D))4290return getOrCreateMethodType(Method, F);42914292const auto *FTy = FnType->getAs<FunctionType>();4293CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;42944295if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {4296// Add "self" and "_cmd"4297SmallVector<llvm::Metadata *, 16> Elts;42984299// First element is always return type. For 'void' functions it is NULL.4300QualType ResultTy = OMethod->getReturnType();43014302// Replace the instancetype keyword with the actual type.4303if (ResultTy == CGM.getContext().getObjCInstanceType())4304ResultTy = CGM.getContext().getPointerType(4305QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));43064307Elts.push_back(getOrCreateType(ResultTy, F));4308// "self" pointer is always first argument.4309QualType SelfDeclTy;4310if (auto *SelfDecl = OMethod->getSelfDecl())4311SelfDeclTy = SelfDecl->getType();4312else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))4313if (FPT->getNumParams() > 1)4314SelfDeclTy = FPT->getParamType(0);4315if (!SelfDeclTy.isNull())4316Elts.push_back(4317CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));4318// "_cmd" pointer is always second argument.4319Elts.push_back(DBuilder.createArtificialType(4320getOrCreateType(CGM.getContext().getObjCSelType(), F)));4321// Get rest of the arguments.4322for (const auto *PI : OMethod->parameters())4323Elts.push_back(getOrCreateType(PI->getType(), F));4324// Variadic methods need a special marker at the end of the type list.4325if (OMethod->isVariadic())4326Elts.push_back(DBuilder.createUnspecifiedParameter());43274328llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);4329return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,4330getDwarfCC(CC));4331}43324333// Handle variadic function types; they need an additional4334// unspecified parameter.4335if (const auto *FD = dyn_cast<FunctionDecl>(D))4336if (FD->isVariadic()) {4337SmallVector<llvm::Metadata *, 16> EltTys;4338EltTys.push_back(getOrCreateType(FD->getReturnType(), F));4339if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))4340for (QualType ParamType : FPT->param_types())4341EltTys.push_back(getOrCreateType(ParamType, F));4342EltTys.push_back(DBuilder.createUnspecifiedParameter());4343llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);4344return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,4345getDwarfCC(CC));4346}43474348return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));4349}43504351QualType4352CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy,4353const SmallVectorImpl<const VarDecl *> &Args) {4354CallingConv CC = CallingConv::CC_C;4355if (FD)4356if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())4357CC = SrcFnTy->getCallConv();4358SmallVector<QualType, 16> ArgTypes;4359for (const VarDecl *VD : Args)4360ArgTypes.push_back(VD->getType());4361return CGM.getContext().getFunctionType(RetTy, ArgTypes,4362FunctionProtoType::ExtProtoInfo(CC));4363}43644365void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,4366SourceLocation ScopeLoc, QualType FnType,4367llvm::Function *Fn, bool CurFuncIsThunk) {4368StringRef Name;4369StringRef LinkageName;43704371FnBeginRegionCount.push_back(LexicalBlockStack.size());43724373const Decl *D = GD.getDecl();4374bool HasDecl = (D != nullptr);43754376llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;4377llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;4378llvm::DIFile *Unit = getOrCreateFile(Loc);4379llvm::DIScope *FDContext = Unit;4380llvm::DINodeArray TParamsArray;4381if (!HasDecl) {4382// Use llvm function name.4383LinkageName = Fn->getName();4384} else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {4385// If there is a subprogram for this function available then use it.4386auto FI = SPCache.find(FD->getCanonicalDecl());4387if (FI != SPCache.end()) {4388auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);4389if (SP && SP->isDefinition()) {4390LexicalBlockStack.emplace_back(SP);4391RegionMap[D].reset(SP);4392return;4393}4394}4395collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,4396TParamsArray, Flags);4397} else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {4398Name = getObjCMethodName(OMD);4399Flags |= llvm::DINode::FlagPrototyped;4400} else if (isa<VarDecl>(D) &&4401GD.getDynamicInitKind() != DynamicInitKind::NoStub) {4402// This is a global initializer or atexit destructor for a global variable.4403Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),4404Fn);4405} else {4406Name = Fn->getName();44074408if (isa<BlockDecl>(D))4409LinkageName = Name;44104411Flags |= llvm::DINode::FlagPrototyped;4412}4413if (Name.starts_with("\01"))4414Name = Name.substr(1);44154416assert((!D || !isa<VarDecl>(D) ||4417GD.getDynamicInitKind() != DynamicInitKind::NoStub) &&4418"Unexpected DynamicInitKind !");44194420if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||4421isa<VarDecl>(D) || isa<CapturedDecl>(D)) {4422Flags |= llvm::DINode::FlagArtificial;4423// Artificial functions should not silently reuse CurLoc.4424CurLoc = SourceLocation();4425}44264427if (CurFuncIsThunk)4428Flags |= llvm::DINode::FlagThunk;44294430if (Fn->hasLocalLinkage())4431SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;4432if (CGM.getLangOpts().Optimize)4433SPFlags |= llvm::DISubprogram::SPFlagOptimized;44344435llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();4436llvm::DISubprogram::DISPFlags SPFlagsForDef =4437SPFlags | llvm::DISubprogram::SPFlagDefinition;44384439const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);4440unsigned ScopeLine = getLineNumber(ScopeLoc);4441llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);4442llvm::DISubprogram *Decl = nullptr;4443llvm::DINodeArray Annotations = nullptr;4444if (D) {4445Decl = isa<ObjCMethodDecl>(D)4446? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)4447: getFunctionDeclaration(D);4448Annotations = CollectBTFDeclTagAnnotations(D);4449}44504451// FIXME: The function declaration we're constructing here is mostly reusing4452// declarations from CXXMethodDecl and not constructing new ones for arbitrary4453// FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for4454// all subprograms instead of the actual context since subprogram definitions4455// are emitted as CU level entities by the backend.4456llvm::DISubprogram *SP = DBuilder.createFunction(4457FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,4458FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,4459Annotations);4460Fn->setSubprogram(SP);4461// We might get here with a VarDecl in the case we're generating4462// code for the initialization of globals. Do not record these decls4463// as they will overwrite the actual VarDecl Decl in the cache.4464if (HasDecl && isa<FunctionDecl>(D))4465DeclCache[D->getCanonicalDecl()].reset(SP);44664467// Push the function onto the lexical block stack.4468LexicalBlockStack.emplace_back(SP);44694470if (HasDecl)4471RegionMap[D].reset(SP);4472}44734474void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,4475QualType FnType, llvm::Function *Fn) {4476StringRef Name;4477StringRef LinkageName;44784479const Decl *D = GD.getDecl();4480if (!D)4481return;44824483llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {4484return GetName(D, true);4485});44864487llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;4488llvm::DIFile *Unit = getOrCreateFile(Loc);4489bool IsDeclForCallSite = Fn ? true : false;4490llvm::DIScope *FDContext =4491IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);4492llvm::DINodeArray TParamsArray;4493if (isa<FunctionDecl>(D)) {4494// If there is a DISubprogram for this function available then use it.4495collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,4496TParamsArray, Flags);4497} else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {4498Name = getObjCMethodName(OMD);4499Flags |= llvm::DINode::FlagPrototyped;4500} else {4501llvm_unreachable("not a function or ObjC method");4502}4503if (!Name.empty() && Name[0] == '\01')4504Name = Name.substr(1);45054506if (D->isImplicit()) {4507Flags |= llvm::DINode::FlagArtificial;4508// Artificial functions without a location should not silently reuse CurLoc.4509if (Loc.isInvalid())4510CurLoc = SourceLocation();4511}4512unsigned LineNo = getLineNumber(Loc);4513unsigned ScopeLine = 0;4514llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;4515if (CGM.getLangOpts().Optimize)4516SPFlags |= llvm::DISubprogram::SPFlagOptimized;45174518llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);4519llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);4520llvm::DISubprogram *SP = DBuilder.createFunction(4521FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,4522SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);45234524// Preserve btf_decl_tag attributes for parameters of extern functions4525// for BPF target. The parameters created in this loop are attached as4526// DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.4527if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {4528if (auto *FD = dyn_cast<FunctionDecl>(D)) {4529llvm::DITypeRefArray ParamTypes = STy->getTypeArray();4530unsigned ArgNo = 1;4531for (ParmVarDecl *PD : FD->parameters()) {4532llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);4533DBuilder.createParameterVariable(4534SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,4535llvm::DINode::FlagZero, ParamAnnotations);4536++ArgNo;4537}4538}4539}45404541if (IsDeclForCallSite)4542Fn->setSubprogram(SP);45434544DBuilder.finalizeSubprogram(SP);4545}45464547void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,4548QualType CalleeType,4549const FunctionDecl *CalleeDecl) {4550if (!CallOrInvoke)4551return;4552auto *Func = CallOrInvoke->getCalledFunction();4553if (!Func)4554return;4555if (Func->getSubprogram())4556return;45574558// Do not emit a declaration subprogram for a function with nodebug4559// attribute, or if call site info isn't required.4560if (CalleeDecl->hasAttr<NoDebugAttr>() ||4561getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)4562return;45634564// If there is no DISubprogram attached to the function being called,4565// create the one describing the function in order to have complete4566// call site debug info.4567if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())4568EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);4569}45704571void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {4572const auto *FD = cast<FunctionDecl>(GD.getDecl());4573// If there is a subprogram for this function available then use it.4574auto FI = SPCache.find(FD->getCanonicalDecl());4575llvm::DISubprogram *SP = nullptr;4576if (FI != SPCache.end())4577SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);4578if (!SP || !SP->isDefinition())4579SP = getFunctionStub(GD);4580FnBeginRegionCount.push_back(LexicalBlockStack.size());4581LexicalBlockStack.emplace_back(SP);4582setInlinedAt(Builder.getCurrentDebugLocation());4583EmitLocation(Builder, FD->getLocation());4584}45854586void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {4587assert(CurInlinedAt && "unbalanced inline scope stack");4588EmitFunctionEnd(Builder, nullptr);4589setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());4590}45914592void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {4593// Update our current location4594setLocation(Loc);45954596if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())4597return;45984599llvm::MDNode *Scope = LexicalBlockStack.back();4600Builder.SetCurrentDebugLocation(4601llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),4602getColumnNumber(CurLoc), Scope, CurInlinedAt));4603}46044605void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {4606llvm::MDNode *Back = nullptr;4607if (!LexicalBlockStack.empty())4608Back = LexicalBlockStack.back().get();4609LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(4610cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),4611getColumnNumber(CurLoc)));4612}46134614void CGDebugInfo::AppendAddressSpaceXDeref(4615unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {4616std::optional<unsigned> DWARFAddressSpace =4617CGM.getTarget().getDWARFAddressSpace(AddressSpace);4618if (!DWARFAddressSpace)4619return;46204621Expr.push_back(llvm::dwarf::DW_OP_constu);4622Expr.push_back(*DWARFAddressSpace);4623Expr.push_back(llvm::dwarf::DW_OP_swap);4624Expr.push_back(llvm::dwarf::DW_OP_xderef);4625}46264627void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,4628SourceLocation Loc) {4629// Set our current location.4630setLocation(Loc);46314632// Emit a line table change for the current location inside the new scope.4633Builder.SetCurrentDebugLocation(llvm::DILocation::get(4634CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),4635LexicalBlockStack.back(), CurInlinedAt));46364637if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)4638return;46394640// Create a new lexical block and push it on the stack.4641CreateLexicalBlock(Loc);4642}46434644void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,4645SourceLocation Loc) {4646assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");46474648// Provide an entry in the line table for the end of the block.4649EmitLocation(Builder, Loc);46504651if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)4652return;46534654LexicalBlockStack.pop_back();4655}46564657void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {4658assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");4659unsigned RCount = FnBeginRegionCount.back();4660assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");46614662// Pop all regions for this function.4663while (LexicalBlockStack.size() != RCount) {4664// Provide an entry in the line table for the end of the block.4665EmitLocation(Builder, CurLoc);4666LexicalBlockStack.pop_back();4667}4668FnBeginRegionCount.pop_back();46694670if (Fn && Fn->getSubprogram())4671DBuilder.finalizeSubprogram(Fn->getSubprogram());4672}46734674CGDebugInfo::BlockByRefType4675CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,4676uint64_t *XOffset) {4677SmallVector<llvm::Metadata *, 5> EltTys;4678QualType FType;4679uint64_t FieldSize, FieldOffset;4680uint32_t FieldAlign;46814682llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());4683QualType Type = VD->getType();46844685FieldOffset = 0;4686FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);4687EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));4688EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));4689FType = CGM.getContext().IntTy;4690EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));4691EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));46924693bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);4694if (HasCopyAndDispose) {4695FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);4696EltTys.push_back(4697CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));4698EltTys.push_back(4699CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));4700}4701bool HasByrefExtendedLayout;4702Qualifiers::ObjCLifetime Lifetime;4703if (CGM.getContext().getByrefLifetime(Type, Lifetime,4704HasByrefExtendedLayout) &&4705HasByrefExtendedLayout) {4706FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);4707EltTys.push_back(4708CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));4709}47104711CharUnits Align = CGM.getContext().getDeclAlign(VD);4712if (Align > CGM.getContext().toCharUnitsFromBits(4713CGM.getTarget().getPointerAlign(LangAS::Default))) {4714CharUnits FieldOffsetInBytes =4715CGM.getContext().toCharUnitsFromBits(FieldOffset);4716CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);4717CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;47184719if (NumPaddingBytes.isPositive()) {4720llvm::APInt pad(32, NumPaddingBytes.getQuantity());4721FType = CGM.getContext().getConstantArrayType(4722CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);4723EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));4724}4725}47264727FType = Type;4728llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);4729FieldSize = CGM.getContext().getTypeSize(FType);4730FieldAlign = CGM.getContext().toBits(Align);47314732*XOffset = FieldOffset;4733llvm::DIType *FieldTy = DBuilder.createMemberType(4734Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,4735llvm::DINode::FlagZero, WrappedTy);4736EltTys.push_back(FieldTy);4737FieldOffset += FieldSize;47384739llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);4740return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,4741llvm::DINode::FlagZero, nullptr, Elements),4742WrappedTy};4743}47444745llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,4746llvm::Value *Storage,4747std::optional<unsigned> ArgNo,4748CGBuilderTy &Builder,4749const bool UsePointerValue) {4750assert(CGM.getCodeGenOpts().hasReducedDebugInfo());4751assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");4752if (VD->hasAttr<NoDebugAttr>())4753return nullptr;47544755bool Unwritten =4756VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&4757cast<Decl>(VD->getDeclContext())->isImplicit());4758llvm::DIFile *Unit = nullptr;4759if (!Unwritten)4760Unit = getOrCreateFile(VD->getLocation());4761llvm::DIType *Ty;4762uint64_t XOffset = 0;4763if (VD->hasAttr<BlocksAttr>())4764Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;4765else4766Ty = getOrCreateType(VD->getType(), Unit);47674768// If there is no debug info for this type then do not emit debug info4769// for this variable.4770if (!Ty)4771return nullptr;47724773// Get location information.4774unsigned Line = 0;4775unsigned Column = 0;4776if (!Unwritten) {4777Line = getLineNumber(VD->getLocation());4778Column = getColumnNumber(VD->getLocation());4779}4780SmallVector<uint64_t, 13> Expr;4781llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;4782if (VD->isImplicit())4783Flags |= llvm::DINode::FlagArtificial;47844785auto Align = getDeclAlignIfRequired(VD, CGM.getContext());47864787unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());4788AppendAddressSpaceXDeref(AddressSpace, Expr);47894790// If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an4791// object pointer flag.4792if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {4793if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||4794IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)4795Flags |= llvm::DINode::FlagObjectPointer;4796}47974798// Note: Older versions of clang used to emit byval references with an extra4799// DW_OP_deref, because they referenced the IR arg directly instead of4800// referencing an alloca. Newer versions of LLVM don't treat allocas4801// differently from other function arguments when used in a dbg.declare.4802auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());4803StringRef Name = VD->getName();4804if (!Name.empty()) {4805// __block vars are stored on the heap if they are captured by a block that4806// can escape the local scope.4807if (VD->isEscapingByref()) {4808// Here, we need an offset *into* the alloca.4809CharUnits offset = CharUnits::fromQuantity(32);4810Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);4811// offset of __forwarding field4812offset = CGM.getContext().toCharUnitsFromBits(4813CGM.getTarget().getPointerWidth(LangAS::Default));4814Expr.push_back(offset.getQuantity());4815Expr.push_back(llvm::dwarf::DW_OP_deref);4816Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);4817// offset of x field4818offset = CGM.getContext().toCharUnitsFromBits(XOffset);4819Expr.push_back(offset.getQuantity());4820}4821} else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {4822// If VD is an anonymous union then Storage represents value for4823// all union fields.4824const RecordDecl *RD = RT->getDecl();4825if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {4826// GDB has trouble finding local variables in anonymous unions, so we emit4827// artificial local variables for each of the members.4828//4829// FIXME: Remove this code as soon as GDB supports this.4830// The debug info verifier in LLVM operates based on the assumption that a4831// variable has the same size as its storage and we had to disable the4832// check for artificial variables.4833for (const auto *Field : RD->fields()) {4834llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);4835StringRef FieldName = Field->getName();48364837// Ignore unnamed fields. Do not ignore unnamed records.4838if (FieldName.empty() && !isa<RecordType>(Field->getType()))4839continue;48404841// Use VarDecl's Tag, Scope and Line number.4842auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());4843auto *D = DBuilder.createAutoVariable(4844Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,4845Flags | llvm::DINode::FlagArtificial, FieldAlign);48464847// Insert an llvm.dbg.declare into the current block.4848DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),4849llvm::DILocation::get(CGM.getLLVMContext(), Line,4850Column, Scope,4851CurInlinedAt),4852Builder.GetInsertBlock());4853}4854}4855}48564857// Clang stores the sret pointer provided by the caller in a static alloca.4858// Use DW_OP_deref to tell the debugger to load the pointer and treat it as4859// the address of the variable.4860if (UsePointerValue) {4861assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&4862"Debug info already contains DW_OP_deref.");4863Expr.push_back(llvm::dwarf::DW_OP_deref);4864}48654866// Create the descriptor for the variable.4867llvm::DILocalVariable *D = nullptr;4868if (ArgNo) {4869llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);4870D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,4871CGM.getLangOpts().Optimize, Flags,4872Annotations);4873} else {4874// For normal local variable, we will try to find out whether 'VD' is the4875// copy parameter of coroutine.4876// If yes, we are going to use DIVariable of the origin parameter instead4877// of creating the new one.4878// If no, it might be a normal alloc, we just create a new one for it.48794880// Check whether the VD is move parameters.4881auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {4882// The scope of parameter and move-parameter should be distinct4883// DISubprogram.4884if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())4885return nullptr;48864887auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {4888Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);4889if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {4890DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();4891Decl *Decl = DeclGroup.getSingleDecl();4892if (VD == dyn_cast_or_null<VarDecl>(Decl))4893return true;4894}4895return false;4896});48974898if (Iter != CoroutineParameterMappings.end()) {4899ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);4900auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {4901return DbgPair.first == PD && DbgPair.second->getScope() == Scope;4902});4903if (Iter2 != ParamDbgMappings.end())4904return const_cast<llvm::DILocalVariable *>(Iter2->second);4905}4906return nullptr;4907};49084909// If we couldn't find a move param DIVariable, create a new one.4910D = RemapCoroArgToLocalVar();4911// Or we will create a new DIVariable for this Decl if D dose not exists.4912if (!D)4913D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,4914CGM.getLangOpts().Optimize, Flags, Align);4915}4916// Insert an llvm.dbg.declare into the current block.4917DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),4918llvm::DILocation::get(CGM.getLLVMContext(), Line,4919Column, Scope, CurInlinedAt),4920Builder.GetInsertBlock());49214922return D;4923}49244925llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,4926llvm::Value *Storage,4927std::optional<unsigned> ArgNo,4928CGBuilderTy &Builder,4929const bool UsePointerValue) {4930assert(CGM.getCodeGenOpts().hasReducedDebugInfo());4931assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");4932if (BD->hasAttr<NoDebugAttr>())4933return nullptr;49344935// Skip the tuple like case, we don't handle that here4936if (isa<DeclRefExpr>(BD->getBinding()))4937return nullptr;49384939llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());4940llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);49414942// If there is no debug info for this type then do not emit debug info4943// for this variable.4944if (!Ty)4945return nullptr;49464947auto Align = getDeclAlignIfRequired(BD, CGM.getContext());4948unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());49494950SmallVector<uint64_t, 3> Expr;4951AppendAddressSpaceXDeref(AddressSpace, Expr);49524953// Clang stores the sret pointer provided by the caller in a static alloca.4954// Use DW_OP_deref to tell the debugger to load the pointer and treat it as4955// the address of the variable.4956if (UsePointerValue) {4957assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&4958"Debug info already contains DW_OP_deref.");4959Expr.push_back(llvm::dwarf::DW_OP_deref);4960}49614962unsigned Line = getLineNumber(BD->getLocation());4963unsigned Column = getColumnNumber(BD->getLocation());4964StringRef Name = BD->getName();4965auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());4966// Create the descriptor for the variable.4967llvm::DILocalVariable *D = DBuilder.createAutoVariable(4968Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,4969llvm::DINode::FlagZero, Align);49704971if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {4972if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {4973const unsigned fieldIndex = FD->getFieldIndex();4974const clang::CXXRecordDecl *parent =4975(const CXXRecordDecl *)FD->getParent();4976const ASTRecordLayout &layout =4977CGM.getContext().getASTRecordLayout(parent);4978const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);4979if (FD->isBitField()) {4980const CGRecordLayout &RL =4981CGM.getTypes().getCGRecordLayout(FD->getParent());4982const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);4983// Use DW_OP_plus_uconst to adjust to the start of the bitfield4984// storage.4985if (!Info.StorageOffset.isZero()) {4986Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);4987Expr.push_back(Info.StorageOffset.getQuantity());4988}4989// Use LLVM_extract_bits to extract the appropriate bits from this4990// bitfield.4991Expr.push_back(Info.IsSigned4992? llvm::dwarf::DW_OP_LLVM_extract_bits_sext4993: llvm::dwarf::DW_OP_LLVM_extract_bits_zext);4994Expr.push_back(Info.Offset);4995// If we have an oversized bitfield then the value won't be more than4996// the size of the type.4997const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());4998Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));4999} else if (fieldOffset != 0) {5000assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&5001"Unexpected non-bitfield with non-byte-aligned offset");5002Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);5003Expr.push_back(5004CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());5005}5006}5007} else if (const ArraySubscriptExpr *ASE =5008dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {5009if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {5010const uint64_t value = IL->getValue().getZExtValue();5011const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());50125013if (value != 0) {5014Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);5015Expr.push_back(CGM.getContext()5016.toCharUnitsFromBits(value * typeSize)5017.getQuantity());5018}5019}5020}50215022// Insert an llvm.dbg.declare into the current block.5023DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),5024llvm::DILocation::get(CGM.getLLVMContext(), Line,5025Column, Scope, CurInlinedAt),5026Builder.GetInsertBlock());50275028return D;5029}50305031llvm::DILocalVariable *5032CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,5033CGBuilderTy &Builder,5034const bool UsePointerValue) {5035assert(CGM.getCodeGenOpts().hasReducedDebugInfo());50365037if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {5038for (auto *B : DD->bindings()) {5039EmitDeclare(B, Storage, std::nullopt, Builder,5040VD->getType()->isReferenceType());5041}5042// Don't emit an llvm.dbg.declare for the composite storage as it doesn't5043// correspond to a user variable.5044return nullptr;5045}50465047return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);5048}50495050void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {5051assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5052assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");50535054if (D->hasAttr<NoDebugAttr>())5055return;50565057auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());5058llvm::DIFile *Unit = getOrCreateFile(D->getLocation());50595060// Get location information.5061unsigned Line = getLineNumber(D->getLocation());5062unsigned Column = getColumnNumber(D->getLocation());50635064StringRef Name = D->getName();50655066// Create the descriptor for the label.5067auto *L =5068DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);50695070// Insert an llvm.dbg.label into the current block.5071DBuilder.insertLabel(L,5072llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,5073Scope, CurInlinedAt),5074Builder.GetInsertBlock());5075}50765077llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,5078llvm::DIType *Ty) {5079llvm::DIType *CachedTy = getTypeOrNull(QualTy);5080if (CachedTy)5081Ty = CachedTy;5082return DBuilder.createObjectPointerType(Ty);5083}50845085void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(5086const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,5087const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {5088assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5089assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");50905091if (Builder.GetInsertBlock() == nullptr)5092return;5093if (VD->hasAttr<NoDebugAttr>())5094return;50955096bool isByRef = VD->hasAttr<BlocksAttr>();50975098uint64_t XOffset = 0;5099llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());5100llvm::DIType *Ty;5101if (isByRef)5102Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;5103else5104Ty = getOrCreateType(VD->getType(), Unit);51055106// Self is passed along as an implicit non-arg variable in a5107// block. Mark it as the object pointer.5108if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))5109if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)5110Ty = CreateSelfType(VD->getType(), Ty);51115112// Get location information.5113const unsigned Line =5114getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);5115unsigned Column = getColumnNumber(VD->getLocation());51165117const llvm::DataLayout &target = CGM.getDataLayout();51185119CharUnits offset = CharUnits::fromQuantity(5120target.getStructLayout(blockInfo.StructureType)5121->getElementOffset(blockInfo.getCapture(VD).getIndex()));51225123SmallVector<uint64_t, 9> addr;5124addr.push_back(llvm::dwarf::DW_OP_deref);5125addr.push_back(llvm::dwarf::DW_OP_plus_uconst);5126addr.push_back(offset.getQuantity());5127if (isByRef) {5128addr.push_back(llvm::dwarf::DW_OP_deref);5129addr.push_back(llvm::dwarf::DW_OP_plus_uconst);5130// offset of __forwarding field5131offset =5132CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));5133addr.push_back(offset.getQuantity());5134addr.push_back(llvm::dwarf::DW_OP_deref);5135addr.push_back(llvm::dwarf::DW_OP_plus_uconst);5136// offset of x field5137offset = CGM.getContext().toCharUnitsFromBits(XOffset);5138addr.push_back(offset.getQuantity());5139}51405141// Create the descriptor for the variable.5142auto Align = getDeclAlignIfRequired(VD, CGM.getContext());5143auto *D = DBuilder.createAutoVariable(5144cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,5145Line, Ty, false, llvm::DINode::FlagZero, Align);51465147// Insert an llvm.dbg.declare into the current block.5148auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,5149LexicalBlockStack.back(), CurInlinedAt);5150auto *Expr = DBuilder.createExpression(addr);5151if (InsertPoint)5152DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);5153else5154DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());5155}51565157llvm::DILocalVariable *5158CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,5159unsigned ArgNo, CGBuilderTy &Builder,5160bool UsePointerValue) {5161assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5162return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);5163}51645165namespace {5166struct BlockLayoutChunk {5167uint64_t OffsetInBits;5168const BlockDecl::Capture *Capture;5169};5170bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {5171return l.OffsetInBits < r.OffsetInBits;5172}5173} // namespace51745175void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(5176const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,5177const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,5178SmallVectorImpl<llvm::Metadata *> &Fields) {5179// Blocks in OpenCL have unique constraints which make the standard fields5180// redundant while requiring size and align fields for enqueue_kernel. See5181// initializeForBlockHeader in CGBlocks.cpp5182if (CGM.getLangOpts().OpenCL) {5183Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,5184BlockLayout.getElementOffsetInBits(0),5185Unit, Unit));5186Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,5187BlockLayout.getElementOffsetInBits(1),5188Unit, Unit));5189} else {5190Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,5191BlockLayout.getElementOffsetInBits(0),5192Unit, Unit));5193Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,5194BlockLayout.getElementOffsetInBits(1),5195Unit, Unit));5196Fields.push_back(5197createFieldType("__reserved", Context.IntTy, Loc, AS_public,5198BlockLayout.getElementOffsetInBits(2), Unit, Unit));5199auto *FnTy = Block.getBlockExpr()->getFunctionType();5200auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());5201Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,5202BlockLayout.getElementOffsetInBits(3),5203Unit, Unit));5204Fields.push_back(createFieldType(5205"__descriptor",5206Context.getPointerType(Block.NeedsCopyDispose5207? Context.getBlockDescriptorExtendedType()5208: Context.getBlockDescriptorType()),5209Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));5210}5211}52125213void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,5214StringRef Name,5215unsigned ArgNo,5216llvm::AllocaInst *Alloca,5217CGBuilderTy &Builder) {5218assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5219ASTContext &C = CGM.getContext();5220const BlockDecl *blockDecl = block.getBlockDecl();52215222// Collect some general information about the block's location.5223SourceLocation loc = blockDecl->getCaretLocation();5224llvm::DIFile *tunit = getOrCreateFile(loc);5225unsigned line = getLineNumber(loc);5226unsigned column = getColumnNumber(loc);52275228// Build the debug-info type for the block literal.5229getDeclContextDescriptor(blockDecl);52305231const llvm::StructLayout *blockLayout =5232CGM.getDataLayout().getStructLayout(block.StructureType);52335234SmallVector<llvm::Metadata *, 16> fields;5235collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,5236fields);52375238// We want to sort the captures by offset, not because DWARF5239// requires this, but because we're paranoid about debuggers.5240SmallVector<BlockLayoutChunk, 8> chunks;52415242// 'this' capture.5243if (blockDecl->capturesCXXThis()) {5244BlockLayoutChunk chunk;5245chunk.OffsetInBits =5246blockLayout->getElementOffsetInBits(block.CXXThisIndex);5247chunk.Capture = nullptr;5248chunks.push_back(chunk);5249}52505251// Variable captures.5252for (const auto &capture : blockDecl->captures()) {5253const VarDecl *variable = capture.getVariable();5254const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);52555256// Ignore constant captures.5257if (captureInfo.isConstant())5258continue;52595260BlockLayoutChunk chunk;5261chunk.OffsetInBits =5262blockLayout->getElementOffsetInBits(captureInfo.getIndex());5263chunk.Capture = &capture;5264chunks.push_back(chunk);5265}52665267// Sort by offset.5268llvm::array_pod_sort(chunks.begin(), chunks.end());52695270for (const BlockLayoutChunk &Chunk : chunks) {5271uint64_t offsetInBits = Chunk.OffsetInBits;5272const BlockDecl::Capture *capture = Chunk.Capture;52735274// If we have a null capture, this must be the C++ 'this' capture.5275if (!capture) {5276QualType type;5277if (auto *Method =5278cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))5279type = Method->getThisType();5280else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))5281type = QualType(RDecl->getTypeForDecl(), 0);5282else5283llvm_unreachable("unexpected block declcontext");52845285fields.push_back(createFieldType("this", type, loc, AS_public,5286offsetInBits, tunit, tunit));5287continue;5288}52895290const VarDecl *variable = capture->getVariable();5291StringRef name = variable->getName();52925293llvm::DIType *fieldType;5294if (capture->isByRef()) {5295TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);5296auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;5297// FIXME: This recomputes the layout of the BlockByRefWrapper.5298uint64_t xoffset;5299fieldType =5300EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;5301fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);5302fieldType = DBuilder.createMemberType(tunit, name, tunit, line,5303PtrInfo.Width, Align, offsetInBits,5304llvm::DINode::FlagZero, fieldType);5305} else {5306auto Align = getDeclAlignIfRequired(variable, CGM.getContext());5307fieldType = createFieldType(name, variable->getType(), loc, AS_public,5308offsetInBits, Align, tunit, tunit);5309}5310fields.push_back(fieldType);5311}53125313SmallString<36> typeName;5314llvm::raw_svector_ostream(typeName)5315<< "__block_literal_" << CGM.getUniqueBlockCount();53165317llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);53185319llvm::DIType *type =5320DBuilder.createStructType(tunit, typeName.str(), tunit, line,5321CGM.getContext().toBits(block.BlockSize), 0,5322llvm::DINode::FlagZero, nullptr, fieldsArray);5323type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);53245325// Get overall information about the block.5326llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;5327auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());53285329// Create the descriptor for the parameter.5330auto *debugVar = DBuilder.createParameterVariable(5331scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);53325333// Insert an llvm.dbg.declare into the current block.5334DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),5335llvm::DILocation::get(CGM.getLLVMContext(), line,5336column, scope, CurInlinedAt),5337Builder.GetInsertBlock());5338}53395340llvm::DIDerivedType *5341CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {5342if (!D || !D->isStaticDataMember())5343return nullptr;53445345auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());5346if (MI != StaticDataMemberCache.end()) {5347assert(MI->second && "Static data member declaration should still exist");5348return MI->second;5349}53505351// If the member wasn't found in the cache, lazily construct and add it to the5352// type (used when a limited form of the type is emitted).5353auto DC = D->getDeclContext();5354auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));5355return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));5356}53575358llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(5359const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,5360StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {5361llvm::DIGlobalVariableExpression *GVE = nullptr;53625363for (const auto *Field : RD->fields()) {5364llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);5365StringRef FieldName = Field->getName();53665367// Ignore unnamed fields, but recurse into anonymous records.5368if (FieldName.empty()) {5369if (const auto *RT = dyn_cast<RecordType>(Field->getType()))5370GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,5371Var, DContext);5372continue;5373}5374// Use VarDecl's Tag, Scope and Line number.5375GVE = DBuilder.createGlobalVariableExpression(5376DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,5377Var->hasLocalLinkage());5378Var->addDebugInfo(GVE);5379}5380return GVE;5381}53825383static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);5384static bool ReferencesAnonymousEntity(RecordType *RT) {5385// Unnamed classes/lambdas can't be reconstituted due to a lack of column5386// info we produce in the DWARF, so we can't get Clang's full name back.5387// But so long as it's not one of those, it doesn't matter if some sub-type5388// of the record (a template parameter) can't be reconstituted - because the5389// un-reconstitutable type itself will carry its own name.5390const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());5391if (!RD)5392return false;5393if (!RD->getIdentifier())5394return true;5395auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);5396if (!TSpecial)5397return false;5398return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());5399}5400static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) {5401return llvm::any_of(Args, [&](const TemplateArgument &TA) {5402switch (TA.getKind()) {5403case TemplateArgument::Pack:5404return ReferencesAnonymousEntity(TA.getPackAsArray());5405case TemplateArgument::Type: {5406struct ReferencesAnonymous5407: public RecursiveASTVisitor<ReferencesAnonymous> {5408bool RefAnon = false;5409bool VisitRecordType(RecordType *RT) {5410if (ReferencesAnonymousEntity(RT)) {5411RefAnon = true;5412return false;5413}5414return true;5415}5416};5417ReferencesAnonymous RT;5418RT.TraverseType(TA.getAsType());5419if (RT.RefAnon)5420return true;5421break;5422}5423default:5424break;5425}5426return false;5427});5428}5429namespace {5430struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {5431bool Reconstitutable = true;5432bool VisitVectorType(VectorType *FT) {5433Reconstitutable = false;5434return false;5435}5436bool VisitAtomicType(AtomicType *FT) {5437Reconstitutable = false;5438return false;5439}5440bool VisitType(Type *T) {5441// _BitInt(N) isn't reconstitutable because the bit width isn't encoded in5442// the DWARF, only the byte width.5443if (T->isBitIntType()) {5444Reconstitutable = false;5445return false;5446}5447return true;5448}5449bool TraverseEnumType(EnumType *ET) {5450// Unnamed enums can't be reconstituted due to a lack of column info we5451// produce in the DWARF, so we can't get Clang's full name back.5452if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {5453if (!ED->getIdentifier()) {5454Reconstitutable = false;5455return false;5456}5457if (!ED->isExternallyVisible()) {5458Reconstitutable = false;5459return false;5460}5461}5462return true;5463}5464bool VisitFunctionProtoType(FunctionProtoType *FT) {5465// noexcept is not encoded in DWARF, so the reversi5466Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());5467Reconstitutable &= !FT->getNoReturnAttr();5468return Reconstitutable;5469}5470bool VisitRecordType(RecordType *RT) {5471if (ReferencesAnonymousEntity(RT)) {5472Reconstitutable = false;5473return false;5474}5475return true;5476}5477};5478} // anonymous namespace54795480// Test whether a type name could be rebuilt from emitted debug info.5481static bool IsReconstitutableType(QualType QT) {5482ReconstitutableType T;5483T.TraverseType(QT);5484return T.Reconstitutable;5485}54865487bool CGDebugInfo::HasReconstitutableArgs(5488ArrayRef<TemplateArgument> Args) const {5489return llvm::all_of(Args, [&](const TemplateArgument &TA) {5490switch (TA.getKind()) {5491case TemplateArgument::Template:5492// Easy to reconstitute - the value of the parameter in the debug5493// info is the string name of the template. The template name5494// itself won't benefit from any name rebuilding, but that's a5495// representational limitation - maybe DWARF could be5496// changed/improved to use some more structural representation.5497return true;5498case TemplateArgument::Declaration:5499// Reference and pointer non-type template parameters point to5500// variables, functions, etc and their value is, at best (for5501// variables) represented as an address - not a reference to the5502// DWARF describing the variable/function/etc. This makes it hard,5503// possibly impossible to rebuild the original name - looking up5504// the address in the executable file's symbol table would be5505// needed.5506return false;5507case TemplateArgument::NullPtr:5508// These could be rebuilt, but figured they're close enough to the5509// declaration case, and not worth rebuilding.5510return false;5511case TemplateArgument::Pack:5512// A pack is invalid if any of the elements of the pack are5513// invalid.5514return HasReconstitutableArgs(TA.getPackAsArray());5515case TemplateArgument::Integral:5516// Larger integers get encoded as DWARF blocks which are a bit5517// harder to parse back into a large integer, etc - so punting on5518// this for now. Re-parsing the integers back into APInt is5519// probably feasible some day.5520return TA.getAsIntegral().getBitWidth() <= 64 &&5521IsReconstitutableType(TA.getIntegralType());5522case TemplateArgument::StructuralValue:5523return false;5524case TemplateArgument::Type:5525return IsReconstitutableType(TA.getAsType());5526case TemplateArgument::Expression:5527return IsReconstitutableType(TA.getAsExpr()->getType());5528default:5529llvm_unreachable("Other, unresolved, template arguments should "5530"not be seen here");5531}5532});5533}55345535std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {5536std::string Name;5537llvm::raw_string_ostream OS(Name);5538const NamedDecl *ND = dyn_cast<NamedDecl>(D);5539if (!ND)5540return Name;5541llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =5542CGM.getCodeGenOpts().getDebugSimpleTemplateNames();55435544if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5545TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;55465547std::optional<TemplateArgs> Args;55485549bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);5550if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {5551Args = GetTemplateArgs(RD);5552} else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {5553Args = GetTemplateArgs(FD);5554auto NameKind = ND->getDeclName().getNameKind();5555IsOperatorOverload |=5556NameKind == DeclarationName::CXXOperatorName ||5557NameKind == DeclarationName::CXXConversionFunctionName;5558} else if (auto *VD = dyn_cast<VarDecl>(ND)) {5559Args = GetTemplateArgs(VD);5560}55615562// A conversion operator presents complications/ambiguity if there's a5563// conversion to class template that is itself a template, eg:5564// template<typename T>5565// operator ns::t1<T, int>();5566// This should be named, eg: "operator ns::t1<float, int><float>"5567// (ignoring clang bug that means this is currently "operator t1<float>")5568// but if the arguments were stripped, the consumer couldn't differentiate5569// whether the template argument list for the conversion type was the5570// function's argument list (& no reconstitution was needed) or not.5571// This could be handled if reconstitutable names had a separate attribute5572// annotating them as such - this would remove the ambiguity.5573//5574// Alternatively the template argument list could be parsed enough to check5575// whether there's one list or two, then compare that with the DWARF5576// description of the return type and the template argument lists to determine5577// how many lists there should be and if one is missing it could be assumed(?)5578// to be the function's template argument list & then be rebuilt.5579//5580// Other operator overloads that aren't conversion operators could be5581// reconstituted but would require a bit more nuance about detecting the5582// difference between these different operators during that rebuilding.5583bool Reconstitutable =5584Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;55855586PrintingPolicy PP = getPrintingPolicy();55875588if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||5589!Reconstitutable) {5590ND->getNameForDiagnostic(OS, PP, Qualified);5591} else {5592bool Mangled = TemplateNamesKind ==5593llvm::codegenoptions::DebugTemplateNamesKind::Mangled;5594// check if it's a template5595if (Mangled)5596OS << "_STN|";55975598OS << ND->getDeclName();5599std::string EncodedOriginalName;5600llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);5601EncodedOriginalNameOS << ND->getDeclName();56025603if (Mangled) {5604OS << "|";5605printTemplateArgumentList(OS, Args->Args, PP);5606printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);5607#ifndef NDEBUG5608std::string CanonicalOriginalName;5609llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);5610ND->getNameForDiagnostic(OriginalOS, PP, Qualified);5611assert(EncodedOriginalNameOS.str() == OriginalOS.str());5612#endif5613}5614}5615return Name;5616}56175618void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,5619const VarDecl *D) {5620assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5621if (D->hasAttr<NoDebugAttr>())5622return;56235624llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {5625return GetName(D, true);5626});56275628// If we already created a DIGlobalVariable for this declaration, just attach5629// it to the llvm::GlobalVariable.5630auto Cached = DeclCache.find(D->getCanonicalDecl());5631if (Cached != DeclCache.end())5632return Var->addDebugInfo(5633cast<llvm::DIGlobalVariableExpression>(Cached->second));56345635// Create global variable debug descriptor.5636llvm::DIFile *Unit = nullptr;5637llvm::DIScope *DContext = nullptr;5638unsigned LineNo;5639StringRef DeclName, LinkageName;5640QualType T;5641llvm::MDTuple *TemplateParameters = nullptr;5642collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,5643TemplateParameters, DContext);56445645// Attempt to store one global variable for the declaration - even if we5646// emit a lot of fields.5647llvm::DIGlobalVariableExpression *GVE = nullptr;56485649// If this is an anonymous union then we'll want to emit a global5650// variable for each member of the anonymous union so that it's possible5651// to find the name of any field in the union.5652if (T->isUnionType() && DeclName.empty()) {5653const RecordDecl *RD = T->castAs<RecordType>()->getDecl();5654assert(RD->isAnonymousStructOrUnion() &&5655"unnamed non-anonymous struct or union?");5656GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);5657} else {5658auto Align = getDeclAlignIfRequired(D, CGM.getContext());56595660SmallVector<uint64_t, 4> Expr;5661unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());5662if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {5663if (D->hasAttr<CUDASharedAttr>())5664AddressSpace =5665CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);5666else if (D->hasAttr<CUDAConstantAttr>())5667AddressSpace =5668CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);5669}5670AppendAddressSpaceXDeref(AddressSpace, Expr);56715672llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);5673GVE = DBuilder.createGlobalVariableExpression(5674DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),5675Var->hasLocalLinkage(), true,5676Expr.empty() ? nullptr : DBuilder.createExpression(Expr),5677getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,5678Align, Annotations);5679Var->addDebugInfo(GVE);5680}5681DeclCache[D->getCanonicalDecl()].reset(GVE);5682}56835684void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {5685assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5686if (VD->hasAttr<NoDebugAttr>())5687return;5688llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {5689return GetName(VD, true);5690});56915692auto Align = getDeclAlignIfRequired(VD, CGM.getContext());5693// Create the descriptor for the variable.5694llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());5695StringRef Name = VD->getName();5696llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);56975698if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {5699const auto *ED = cast<EnumDecl>(ECD->getDeclContext());5700assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");57015702if (CGM.getCodeGenOpts().EmitCodeView) {5703// If CodeView, emit enums as global variables, unless they are defined5704// inside a class. We do this because MSVC doesn't emit S_CONSTANTs for5705// enums in classes, and because it is difficult to attach this scope5706// information to the global variable.5707if (isa<RecordDecl>(ED->getDeclContext()))5708return;5709} else {5710// If not CodeView, emit DW_TAG_enumeration_type if necessary. For5711// example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the5712// first time `ZERO` is referenced in a function.5713llvm::DIType *EDTy =5714getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);5715assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);5716(void)EDTy;5717return;5718}5719}57205721// Do not emit separate definitions for function local consts.5722if (isa<FunctionDecl>(VD->getDeclContext()))5723return;57245725VD = cast<ValueDecl>(VD->getCanonicalDecl());5726auto *VarD = dyn_cast<VarDecl>(VD);5727if (VarD && VarD->isStaticDataMember()) {5728auto *RD = cast<RecordDecl>(VarD->getDeclContext());5729getDeclContextDescriptor(VarD);5730// Ensure that the type is retained even though it's otherwise unreferenced.5731//5732// FIXME: This is probably unnecessary, since Ty should reference RD5733// through its scope.5734RetainedTypes.push_back(5735CGM.getContext().getRecordType(RD).getAsOpaquePtr());57365737return;5738}5739llvm::DIScope *DContext = getDeclContextDescriptor(VD);57405741auto &GV = DeclCache[VD];5742if (GV)5743return;57445745llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);5746llvm::MDTuple *TemplateParameters = nullptr;57475748if (isa<VarTemplateSpecializationDecl>(VD))5749if (VarD) {5750llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);5751TemplateParameters = parameterNodes.get();5752}57535754GV.reset(DBuilder.createGlobalVariableExpression(5755DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,5756true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),5757TemplateParameters, Align));5758}57595760void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,5761const VarDecl *D) {5762assert(CGM.getCodeGenOpts().hasReducedDebugInfo());5763if (D->hasAttr<NoDebugAttr>())5764return;57655766auto Align = getDeclAlignIfRequired(D, CGM.getContext());5767llvm::DIFile *Unit = getOrCreateFile(D->getLocation());5768StringRef Name = D->getName();5769llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);57705771llvm::DIScope *DContext = getDeclContextDescriptor(D);5772llvm::DIGlobalVariableExpression *GVE =5773DBuilder.createGlobalVariableExpression(5774DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),5775Ty, false, false, nullptr, nullptr, nullptr, Align);5776Var->addDebugInfo(GVE);5777}57785779void CGDebugInfo::EmitPseudoVariable(CGBuilderTy &Builder,5780llvm::Instruction *Value, QualType Ty) {5781// Only when -g2 or above is specified, debug info for variables will be5782// generated.5783if (CGM.getCodeGenOpts().getDebugInfo() <=5784llvm::codegenoptions::DebugLineTablesOnly)5785return;57865787llvm::DILocation *DIL = Value->getDebugLoc().get();5788if (!DIL)5789return;57905791llvm::DIFile *Unit = DIL->getFile();5792llvm::DIType *Type = getOrCreateType(Ty, Unit);57935794// Check if Value is already a declared variable and has debug info, in this5795// case we have nothing to do. Clang emits a declared variable as alloca, and5796// it is loaded upon use, so we identify such pattern here.5797if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {5798llvm::Value *Var = Load->getPointerOperand();5799// There can be implicit type cast applied on a variable if it is an opaque5800// ptr, in this case its debug info may not match the actual type of object5801// being used as in the next instruction, so we will need to emit a pseudo5802// variable for type-casted value.5803auto DeclareTypeMatches = [&](auto *DbgDeclare) {5804return DbgDeclare->getVariable()->getType() == Type;5805};5806if (any_of(llvm::findDbgDeclares(Var), DeclareTypeMatches) ||5807any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))5808return;5809}58105811llvm::DILocalVariable *D =5812DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,5813Type, false, llvm::DINode::FlagArtificial);58145815if (auto InsertPoint = Value->getInsertionPointAfterDef()) {5816DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,5817&**InsertPoint);5818}5819}58205821void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,5822const GlobalDecl GD) {58235824assert(GV);58255826if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5827return;58285829const auto *D = cast<ValueDecl>(GD.getDecl());5830if (D->hasAttr<NoDebugAttr>())5831return;58325833auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());5834llvm::DINode *DI;58355836if (!AliaseeDecl)5837// FIXME: Aliasee not declared yet - possibly declared later5838// For example,5839//5840// 1 extern int newname __attribute__((alias("oldname")));5841// 2 int oldname = 1;5842//5843// No debug info would be generated for 'newname' in this case.5844//5845// Fix compiler to generate "newname" as imported_declaration5846// pointing to the DIE of "oldname".5847return;5848if (!(DI = getDeclarationOrDefinition(5849AliaseeDecl.getCanonicalDecl().getDecl())))5850return;58515852llvm::DIScope *DContext = getDeclContextDescriptor(D);5853auto Loc = D->getLocation();58545855llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(5856DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());58575858// Record this DIE in the cache for nested declaration reference.5859ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);5860}58615862void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,5863const StringLiteral *S) {5864SourceLocation Loc = S->getStrTokenLoc(0);5865PresumedLoc PLoc = CGM.getContext().getSourceManager().getPresumedLoc(Loc);5866if (!PLoc.isValid())5867return;58685869llvm::DIFile *File = getOrCreateFile(Loc);5870llvm::DIGlobalVariableExpression *Debug =5871DBuilder.createGlobalVariableExpression(5872nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),5873getLineNumber(Loc), getOrCreateType(S->getType(), File), true);5874GV->addDebugInfo(Debug);5875}58765877llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {5878if (!LexicalBlockStack.empty())5879return LexicalBlockStack.back();5880llvm::DIScope *Mod = getParentModuleOrNull(D);5881return getContextDescriptor(D, Mod ? Mod : TheCU);5882}58835884void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {5885if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5886return;5887const NamespaceDecl *NSDecl = UD.getNominatedNamespace();5888if (!NSDecl->isAnonymousNamespace() ||5889CGM.getCodeGenOpts().DebugExplicitImport) {5890auto Loc = UD.getLocation();5891if (!Loc.isValid())5892Loc = CurLoc;5893DBuilder.createImportedModule(5894getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),5895getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));5896}5897}58985899void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {5900if (llvm::DINode *Target =5901getDeclarationOrDefinition(USD.getUnderlyingDecl())) {5902auto Loc = USD.getLocation();5903DBuilder.createImportedDeclaration(5904getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,5905getOrCreateFile(Loc), getLineNumber(Loc));5906}5907}59085909void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {5910if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5911return;5912assert(UD.shadow_size() &&5913"We shouldn't be codegening an invalid UsingDecl containing no decls");59145915for (const auto *USD : UD.shadows()) {5916// FIXME: Skip functions with undeduced auto return type for now since we5917// don't currently have the plumbing for separate declarations & definitions5918// of free functions and mismatched types (auto in the declaration, concrete5919// return type in the definition)5920if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))5921if (const auto *AT = FD->getType()5922->castAs<FunctionProtoType>()5923->getContainedAutoType())5924if (AT->getDeducedType().isNull())5925continue;59265927EmitUsingShadowDecl(*USD);5928// Emitting one decl is sufficient - debuggers can detect that this is an5929// overloaded name & provide lookup for all the overloads.5930break;5931}5932}59335934void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {5935if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5936return;5937assert(UD.shadow_size() &&5938"We shouldn't be codegening an invalid UsingEnumDecl"5939" containing no decls");59405941for (const auto *USD : UD.shadows())5942EmitUsingShadowDecl(*USD);5943}59445945void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {5946if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)5947return;5948if (Module *M = ID.getImportedModule()) {5949auto Info = ASTSourceDescriptor(*M);5950auto Loc = ID.getLocation();5951DBuilder.createImportedDeclaration(5952getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),5953getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),5954getLineNumber(Loc));5955}5956}59575958llvm::DIImportedEntity *5959CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {5960if (!CGM.getCodeGenOpts().hasReducedDebugInfo())5961return nullptr;5962auto &VH = NamespaceAliasCache[&NA];5963if (VH)5964return cast<llvm::DIImportedEntity>(VH);5965llvm::DIImportedEntity *R;5966auto Loc = NA.getLocation();5967if (const auto *Underlying =5968dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))5969// This could cache & dedup here rather than relying on metadata deduping.5970R = DBuilder.createImportedDeclaration(5971getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),5972EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),5973getLineNumber(Loc), NA.getName());5974else5975R = DBuilder.createImportedDeclaration(5976getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),5977getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),5978getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());5979VH.reset(R);5980return R;5981}59825983llvm::DINamespace *5984CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {5985// Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued5986// if necessary, and this way multiple declarations of the same namespace in5987// different parent modules stay distinct.5988auto I = NamespaceCache.find(NSDecl);5989if (I != NamespaceCache.end())5990return cast<llvm::DINamespace>(I->second);59915992llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);5993// Don't trust the context if it is a DIModule (see comment above).5994llvm::DINamespace *NS =5995DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());5996NamespaceCache[NSDecl].reset(NS);5997return NS;5998}59996000void CGDebugInfo::setDwoId(uint64_t Signature) {6001assert(TheCU && "no main compile unit");6002TheCU->setDWOId(Signature);6003}60046005void CGDebugInfo::finalize() {6006// Creating types might create further types - invalidating the current6007// element and the size(), so don't cache/reference them.6008for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {6009ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];6010llvm::DIType *Ty = E.Type->getDecl()->getDefinition()6011? CreateTypeDefinition(E.Type, E.Unit)6012: E.Decl;6013DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);6014}60156016// Add methods to interface.6017for (const auto &P : ObjCMethodCache) {6018if (P.second.empty())6019continue;60206021QualType QTy(P.first->getTypeForDecl(), 0);6022auto It = TypeCache.find(QTy.getAsOpaquePtr());6023assert(It != TypeCache.end());60246025llvm::DICompositeType *InterfaceDecl =6026cast<llvm::DICompositeType>(It->second);60276028auto CurElts = InterfaceDecl->getElements();6029SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());60306031// For DWARF v4 or earlier, only add objc_direct methods.6032for (auto &SubprogramDirect : P.second)6033if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())6034EltTys.push_back(SubprogramDirect.getPointer());60356036llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);6037DBuilder.replaceArrays(InterfaceDecl, Elements);6038}60396040for (const auto &P : ReplaceMap) {6041assert(P.second);6042auto *Ty = cast<llvm::DIType>(P.second);6043assert(Ty->isForwardDecl());60446045auto It = TypeCache.find(P.first);6046assert(It != TypeCache.end());6047assert(It->second);60486049DBuilder.replaceTemporary(llvm::TempDIType(Ty),6050cast<llvm::DIType>(It->second));6051}60526053for (const auto &P : FwdDeclReplaceMap) {6054assert(P.second);6055llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));6056llvm::Metadata *Repl;60576058auto It = DeclCache.find(P.first);6059// If there has been no definition for the declaration, call RAUW6060// with ourselves, that will destroy the temporary MDNode and6061// replace it with a standard one, avoiding leaking memory.6062if (It == DeclCache.end())6063Repl = P.second;6064else6065Repl = It->second;60666067if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))6068Repl = GVE->getVariable();6069DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));6070}60716072// We keep our own list of retained types, because we need to look6073// up the final type in the type cache.6074for (auto &RT : RetainedTypes)6075if (auto MD = TypeCache[RT])6076DBuilder.retainType(cast<llvm::DIType>(MD));60776078DBuilder.finalize();6079}60806081// Don't ignore in case of explicit cast where it is referenced indirectly.6082void CGDebugInfo::EmitExplicitCastType(QualType Ty) {6083if (CGM.getCodeGenOpts().hasReducedDebugInfo())6084if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))6085DBuilder.retainType(DieTy);6086}60876088void CGDebugInfo::EmitAndRetainType(QualType Ty) {6089if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())6090if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))6091DBuilder.retainType(DieTy);6092}60936094llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {6095if (LexicalBlockStack.empty())6096return llvm::DebugLoc();60976098llvm::MDNode *Scope = LexicalBlockStack.back();6099return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),6100getColumnNumber(Loc), Scope);6101}61026103llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {6104// Call site-related attributes are only useful in optimized programs, and6105// when there's a possibility of debugging backtraces.6106if (!CGM.getLangOpts().Optimize ||6107DebugKind == llvm::codegenoptions::NoDebugInfo ||6108DebugKind == llvm::codegenoptions::LocTrackingOnly)6109return llvm::DINode::FlagZero;61106111// Call site-related attributes are available in DWARF v5. Some debuggers,6112// while not fully DWARF v5-compliant, may accept these attributes as if they6113// were part of DWARF v4.6114bool SupportsDWARFv4Ext =6115CGM.getCodeGenOpts().DwarfVersion == 4 &&6116(CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||6117CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);61186119if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)6120return llvm::DINode::FlagZero;61216122return llvm::DINode::FlagAllCallsDescribed;6123}61246125llvm::DIExpression *6126CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,6127const APValue &Val) {6128// FIXME: Add a representation for integer constants wider than 64 bits.6129if (CGM.getContext().getTypeSize(VD->getType()) > 64)6130return nullptr;61316132if (Val.isFloat())6133return DBuilder.createConstantValueExpression(6134Val.getFloat().bitcastToAPInt().getZExtValue());61356136if (!Val.isInt())6137return nullptr;61386139llvm::APSInt const &ValInt = Val.getInt();6140std::optional<uint64_t> ValIntOpt;6141if (ValInt.isUnsigned())6142ValIntOpt = ValInt.tryZExtValue();6143else if (auto tmp = ValInt.trySExtValue())6144// Transform a signed optional to unsigned optional. When cpp 23 comes,6145// use std::optional::transform6146ValIntOpt = static_cast<uint64_t>(*tmp);61476148if (ValIntOpt)6149return DBuilder.createConstantValueExpression(ValIntOpt.value());61506151return nullptr;6152}615361546155