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