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