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