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