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