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