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